<?php

namespace app\api\controller;

use addons\smsbao\library\Smsbao;
use app\common\controller\Api;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
use think\Cache;

use think\Queue;
use think\cache\driver\Redis;

/**
 * 手机短信接口
 */
class Myshopify extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Feditionordershopify;
        $this->productmodel = new \app\admin\model\ProductsShopify;
    }
    /**
     * 更新销售额---只追踪新订单 旧订单的状态发生改变时候不更新
     * $type 1 测试的时间戳
     * $type 2 本月起始时间戳
     * $type 3 3天前的时间戳
     * $type 4 今天
     *
     * 根据创建日期来判断
     *
     */
    public function savesales($stime = null)
    {

        if (!empty($stime)) {
            $stime_star = strtotime(date("Y-m-d", $stime));
            $stime_end  = $stime_star + 24 * 3600;
            $sql = "select financial_status,sum(countnum) as orders,created_at,gateway,accounturl,DATE_FORMAT(FROM_UNIXTIME(created_at),'%Y-%m-%d') as day,cast(sum(total_price) AS decimal(15,2)) as sum from fa_fedition_ordershopify WHERE gateway IS NOT NULL AND gateway <> '' AND created_at >= '" . $stime_star . "' AND created_at <= '" . $stime_end . "' group by accounturl,day,gateway,financial_status ORDER BY DAY DESC";
        } else {
            $type = $this->request->request('type');
            if ($type == 1) {
                $stime = '1643558399'; //测试的时间戳
            } elseif ($type == 2) {
                $stime = mktime(0, 0, 0, date('m'), 1, date('Y')); //本月起始时间戳
            } elseif ($type == 3) {
                $stime = mktime(0, 0, 0, date('m'), date('d') - 3, date('Y')) - 1; //3天前的时间戳
            } elseif ($type == 4) {
                $stime = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1; //今天
            }
            //根据日期按天排序，再根据类型字段排序
            $sql = "select financial_status,sum(countnum) as orders,created_at,gateway,accounturl,DATE_FORMAT(FROM_UNIXTIME(created_at),'%Y-%m-%d') as day,cast(sum(total_price) AS decimal(15,2)) as sum from fa_fedition_ordershopify WHERE gateway IS NOT NULL AND gateway <> '' AND created_at >= '" . $stime . "' group by accounturl,day,gateway,financial_status ORDER BY DAY DESC";
        }
        $DailyStatistics = \think\Db::query($sql);
        if ($DailyStatistics) {
            foreach ($DailyStatistics as $k => $v) {
                table('fedition_statisticsshopify')
                    ->where('accounturl', $v['accounturl'])
                    ->where('day', $v['day'])
                    ->where('gateway', $v['gateway'])
                    ->delete();
            }
            foreach ($DailyStatistics as $k => $v) {
                $statisticsshopify = table('fedition_statisticsshopify')
                    ->where('accounturl', $v['accounturl'])
                    ->where('day', $v['day'])
                    ->where('gateway', $v['gateway'])
                    ->find();

                $arr['accounturl'] = $v['accounturl'];
                $arr['gateway'] = $v['gateway'];
                $arr['day'] = $v['day'];
                $arr['daystamp'] = $v['created_at'];
                $arr['sum'] = 0;
                $arr['orders'] = 0;
                $arr['refunded'] = 0;
                $arr['refunded_orders'] = 0;
                if ($v['financial_status'] == 'paid') {
                    $arr['sum'] = $v['sum'];
                    $arr['orders'] = $v['orders'];
                }
                //部分退款
                if ($v['financial_status'] == 'partially_refunded') {
                    $arr['sum'] = $v['sum'];
                    $arr['orders'] = $v['orders'];
                }
                if ($v['financial_status'] == 'refunded') {
                    $arr['refunded'] = $v['sum'];
                    $arr['refunded_orders'] = $v['orders'];
                }
                $arr['type'] = 1;
                if (!empty($statisticsshopify)) {
                    $arr['updatetime'] = time();
                    if ($v['financial_status'] == 'paid' || $v['financial_status'] == 'partially_refunded') {
                        $sums = $statisticsshopify['sum'] + $v['sum'];
                        $orderss = $statisticsshopify['orders'] + $v['orders'];
                        $result = table('fedition_statisticsshopify')
                            ->where('accounturl', $v['accounturl'])
                            ->where('day', $v['day'])
                            ->where('gateway', $v['gateway'])
                            ->update(
                                [
                                    'sum' => $sums,
                                    'orders' => $orderss,
                                ]
                            );
                    }
                    if ($v['financial_status'] == 'refunded') {
                        $result = table('fedition_statisticsshopify')
                            ->where('accounturl', $v['accounturl'])
                            ->where('day', $v['day'])
                            ->where('gateway', $v['gateway'])
                            ->update(
                                [
                                    'refunded' => $v['sum'],
                                    'refunded_orders' => $v['orders'],
                                ]
                            );
                    }
                } else {
                    $arr['createtime'] = time();
                    $arr['updatetime'] = time();
                    $result = table('fedition_statisticsshopify')->insert($arr);
                }
                //                $this->addlogshopify(1,$v,2);
            }
        } else {
            //            $this->addlogshopify(0,'',2);
        }
        $this->success('操作成功');
    }

    public function accounturl_iscustom_new()
    {
        $type = $this->request->request('type');
        $id = $this->request->request('id');
        if (!empty($type)) {
            $iscustom = table('fedition_accounturl')
                ->where('id', $id)
                ->find();
            if ($iscustom) {
                $result = $this->orders($iscustom, $type);
            }
        }
        $this->success('操作成功');
    }

    public function test()
    {
        $v['created_at'] = '2022-04-02T10:32:40+08:00';
        $row['created_at'] = strtotime($v['created_at']);
        dump($row['created_at']);
        die;
    }
    /**
     * 后台自动获取数据
     * $type 1 拉取所有订单
     * $type 2 实时拉取当下订单
     * $type 3 拉取之前的订单
     */

    public function accounturl_iscustom()
    {
        $type = $this->request->request('type');

        $where = array();
        $accounturl = $this->request->request('accounturl');
        if (!empty($accounturl)) {
            $where['id'] = $accounturl;
        } else {
            //从56店铺开始更新
            $where['id']  = array('egt', 56);
        }
        if (!empty($type)) {
            $iscustom = table('fedition_accounturl')
                ->where('iscustom', 1)
                ->where('status', 'normal')
                ->where($where)
                ->select();
            if ($iscustom) {
                foreach ($iscustom as $k => $v) {
                    $result = $this->orders($v, $type);
                }
            }
        }
        $this->success('操作成功');
    }
    /**
     * orders
     */
    public function orders($iscustom, $type)
    {
        //    $status
        //        open : 只显示未结订单。
        //        closed : 只显示关闭的订单。
        //        cancelled：仅显示取消的订单。
        //        any：显示任何状态的订单，包括存档订单。
        //        按财务状况过滤订单。
        //    $financial_status
        //        authorized：仅显示授权订单
        //        pending：只显示挂单
        //        paid：仅显示已付款订单
        //        partially_paid : 只显示部分支付的订单
        //        refunded：仅显示已退款的订单
        //        voided : 只显示无效的订单
        //        partially_refunded：仅显示部分退款的订单
        //        any：显示任何财务状况的订单。
        //        unpaid : 显示授权和部分支付的订单
        //        $fulfillment_status
        //            shipped: 已发货
        //            partial: 显示部分发货
        //            unshipped: 显示尚未发货的订单
        //            any: 显示任何履行状态的订单
        //            unfulfilled: 未完成
        $status = 'any';
        $limit = '250';
        $financial_status = 'any';
        $url = $iscustom['shopifyname'] . "/admin/api/2021-07/orders.json";
        if ($type == 3) {
            if (!empty($iscustom['xc_update'])) {
                $created_at_max = $iscustom['xc_update'];
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $created_at_max1 = date('Y-m-d', strtotime("now"));
                $created_at_max2 = date('H:i:s', strtotime("now"));
                $created_at_max = $created_at_max1 . 'T' . $created_at_max2 . '-04:00';
            }
            //拉取之前的订单
            $url = $url . '?created_at_max=' . $created_at_max;
        }
        if ($type == 2) {
            $last_ordershopify = table('fedition_ordershopify')
                ->where('accounturl', $iscustom['id'])
                ->order('ycreated_at desc')
                ->find();
            if ($last_ordershopify) {
                $updated_at_min = $last_ordershopify['ycreated_at'];
                $updated_at_mins = explode('T', $updated_at_min);
                $updated_at_mins[0] = date('Y-m-d', strtotime("$updated_at_mins[0]-1day"));
                $updated_at_min = $updated_at_mins[0] . 'T' . $updated_at_mins[1];
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $updated_at_min = '2021-07-01T00:00:00-04:00';
            }
            //            $url = $url.'?updated_at_min='.$updated_at_min;
            //            $updated_at_min = '2022-03-07T03:24:32+08:00';
            $url = $url . '?created_at_min=' . $updated_at_min;
        }
        if ($type == 1) {
            $url = $url . '?status=' . $status . '&limit=' . $limit . '&financial_status=' . $financial_status;
        } else {
            $url = $url . '&status=' . $status . '&limit=' . $limit . '&financial_status=' . $financial_status;
        }
        $data = $this->geturl($url, $iscustom['shopifyapikey'], $iscustom['shopifysecretapikey']);
        $result = array();
        if ($data) {
            $data = json_decode($data, true);
            if (!empty($data['errors'])) {
                return 2;
            }
            $orders = $data['orders'];
            if (is_array($orders) && !empty($orders)) {
                date_default_timezone_set('Asia/Shanghai');
                $accounturls['xc_update'] = 0;
                foreach ($orders as $k => $v) {
                    $row = $this->model->get($v['id']);
                    $arr['id'] = $v['id'];
                    $arr['name'] = $v['name'];
                    $arr['number'] = $v['number'];
                    $arr['order_number'] = $v['order_number'];
                    //美国时间转北京时间
                    $arr['ycreated_at'] = $v['created_at'];
                    $arr['yupdated_at'] = $v['updated_at'];

                    //改变时间
                    if (!empty($arr['ycreated_at'])) {
                        //直接截取获得时间戳
                        $ycreated_at2 = str_replace('T', ' ', $arr['ycreated_at']);
                        $arr['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '-'));
                    }
                    $arr['created_at'] = strtotime($arr['created_at']);

                    $arr['currency'] = $v['currency'];
                    if (!empty($v['financial_status'])) {
                        $arr['financial_status'] = $v['financial_status'];
                    } else {
                        $arr['financial_status'] = 'unfulfilled';
                    }

                    $arr['ytotal_price'] = $v['total_price'];
                    $arr['total_price'] = $v['total_price'];
                    if (isset($v['customer']['total_spent']) && $v['total_price'] == 0) {
                        $arr['total_price'] = $v['customer']['total_spent'];
                    }
                    if ($arr['financial_status'] == 'refunded') {
                        $arr['total_price'] = 0;
                    }
                    $arr['accounturl'] = $iscustom['id'];
                    $arr['gateway'] = $v['gateway'];
                    $arr['fulfillment_status'] = $v['fulfillment_status'];
                    if ($row) {
                        if ($row['yupdated_at'] !== $arr['yupdated_at']) {
                            $result = $row->save($arr);
                            //订单有更新 发货或者退款
                            //                            $this->addlogshopify(1,$arr,3);
                            // $this->savesales($arr['created_at']);//传时间戳
                        } else {
                            $result = '重复';
                        }
                    } else {
                        $arr['createtime'] = time();
                        $arr['updatetime'] = time();
                        $result = $this->model->insert($arr);
                    }

                    //更新$iscustom['xc_update']
                    $accounturls['xc_update'] = $arr['ycreated_at'];
                }
                table('fedition_accounturl')
                    ->where('id', $iscustom['id'])
                    ->update($accounturls);
            }
            //            $this->addlogshopify(1,$iscustom,1);
        } else {
            //            $this->addlogshopify(0,$iscustom,1);
        }
        return true;
    }

    function geturl($url, $apikey, $secretapikey)
    {
        $headerArray = array("Content-Type:application/json;", 'Authorization:Basic ' . base64_encode("$apikey:$secretapikey"));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function posturl($url, $data = array(), $iscustom = null)
    {
        $data = (is_array($data)) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data;
        $apikey = $iscustom['shopifyapikey'];
        $secretapikey = $iscustom['shopifysecretapikey'];

        $headerArray = array("Content-Type:application/json;", 'Authorization:Basic ' . base64_encode("$apikey:$secretapikey"));
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function posturlopenpx($url, $data = array(), $AccessToken = null)
    {
        $data = (is_array($data)) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data;
        $headerArray = array("Content-type:application/text/plain;charset=UTF-8;");
        if (!empty($AccessToken)) {
            $headerArray[] = $AccessToken;
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * 更新每日汇总
     * $timedate 时间戳
     */
    public function addreportday($timedate = null)
    {
        $where = array();
        if (!empty($timedate)) {
            $where['timedate'] = $timedate;
            $return = $this->reportdayoperation($timedate);
        } else {
            //1.最近七天的条件
            $where['timedate'] = array('gt', strtotime('-5 day'));
            //2.所有的日期
            $alltimedate = table('fedition_report')->field('timedate')->group('timedate')->where($where)->select();
            $return = '';
            if ($alltimedate) {
                foreach ($alltimedate as $k => $v) {
                    $return = $this->reportdayoperation($v['timedate']);
                }
            }
            //3.昨天的日期
            //        $timedate = strtotime('yesterday');
            //        $return = $this->reportdayoperation($timedate);
            //4.今天的日期
            //        $timedate = strtotime('today');
            //        $return = $this->reportdayoperation($timedate);
        }
        $this->success('更新成功！', $return);
    }

    /**
     * reportdayoperation
     */
    public function reportdayoperation($timedate)
    {
        $where['timedate'] = $timedate;
        $where['status'] = 'normal';

        $arr['amount'] = table('fedition_report')->where($where)->sum('amount');
        $arr['advertising'] = table('fedition_report')->where($where)->sum('advertising');
        $arr['sales'] = table('fedition_report')->where($where)->sum('sales');
        $arr['createtime'] = time();
        $arr['updatetime'] = time();
        $arr['timedate'] = $timedate;
        //新增ROI
        if (!empty($arr['advertising']) && !empty($arr['sales'])) {
            $arr['roi'] = '1:' . (float)number_format((float)$arr['sales'] / $arr['advertising'], 3, '.', '');
        } else {
            $arr['roi'] = '0';
        }

        $reportday = table('fedition_reportday')->where('timedate', $timedate)->find();
        if ($reportday) {
            $return = table('fedition_reportday')->where('timedate', $timedate)->update($arr);
        } else {
            $return = table('fedition_reportday')->insert($arr);
        }
        return $return;
    }

    /**
     * 收款账户统计收益
     * $type 1 拉取所有订单
     * $type 2 实时拉取当下订单
     * 网站管理里一个店铺只能有有一条数据
     * 绑定网站管理的admin_id
     * 收款账户--手动修改--与接口gateway数据保持一致
     */
    public function UpdateCollectionAccount()
    {
        $type = $this->request->request('type');
        $stime = '1625068799'; //测试的时间戳
        if ($type == 1) {
            $stime = mktime(0, 0, 0, date('m'), 1, date('Y')); //本月起始时间戳
        } elseif ($type == 2) {
            $stime = mktime(0, 0, 0, date('m'), date('d') - 3, date('Y')) - 1; //3天前的时间戳
        } elseif ($type == 3) {
            $stime = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1; //今天
        }
        $sql = 'SELECT 
a.accounturl,a.`day`,a.daystamp,a.gateway,a.sum,a.refunded
,c.accountpay_id
,d.collection_name
FROM fa_fedition_statisticsshopify as a
LEFT JOIN fa_fedition_website as b 
ON a.accounturl=b.account_address 
LEFT JOIN fa_fedition_websitepaytype as c
ON c.website_id=b.id 
LEFT JOIN fa_fedition_collectiontype as d
ON c.collectiontype_id=d.id 
WHERE a.daystamp>=' . $stime . '
AND a.gateway = d.collection_name
AND b.account_address = c.accounturl_id';
        $statisticsshopify = \think\Db::query($sql);
        //存入数据
        if (!empty($statisticsshopify)) {
            foreach ($statisticsshopify as $k => $v) {
                $data['accountpay_id'] = $v['accountpay_id'];
                $data['accounturl_id'] = $v['accounturl'];
                $data['amount'] = $v['sum'];
                $data['refund_amount'] = $v['refunded'];
                $data['timedate'] = $v['day'];
                $data['daystamp'] = $v['daystamp'];
                if ($v['gateway'] == 'paypal') {
                    $data['type'] = 1;
                }
                if ($v['gateway'] == 'shopify_payments') {
                    $data['type'] = 2;
                }
                if (!empty($data)) {
                    $accountpaystore = table('fedition_accountpaystore')
                        ->where('accountpay_id', $data['accountpay_id'])
                        ->where('accounturl_id', $data['accounturl_id'])
                        ->where('type', $data['type'])
                        ->where('timedate', $data['timedate'])
                        ->find();
                    if ($accountpaystore) {
                        //                        $data['updatetime'] = time();
                        //                        $result = table('fedition_accountpaystore')
                        //                            ->where('accountpay_id',$data['accountpay_id'])
                        //                            ->where('accounturl_id',$data['accounturl_id'])
                        //                            ->where('type',$data['type'])
                        //                            ->where('timedate',$data['timedate'])
                        //                            ->update(
                        //                                [
                        //                                    'amount' => $data['amount'],
                        //                                    'refund_amount' => $data['refund_amount']
                        //                                ]
                        //                            );
                    } else {
                        $data['createtime'] = time();
                        $data['updatetime'] = time();
                        $result = table('fedition_accountpaystore')->insert($data);
                    }
                }
            }
        }
        $this->success('返回数据');
    }

    /**
     * @return null
     */
    public function addlogshopify($status, $data, $type)
    {
        if ($type == 1) {
            if ($status == 0) {
                $data1['msg'] = '参数错误未获取数据';
                $data1['status'] = 'hidden';
            } else {
                $data1['msg'] = '获取接口数据成功';
            }
            $data1['createtime'] = time();
            $data1['updatetime'] = time();
            $data1['type'] = 1;
            $data1['accounturl'] = $data['id'];
            $data1['iscustom'] = $data['iscustom'];
            $data1['shopifyapikey'] = $data['shopifyapikey'];
            $data1['shopifysecretapikey'] = $data['shopifysecretapikey'];
            $data1['shopifyname'] = $data['shopifyname'];
            $return = table('fedition_logshopify')->insert($data1, true);
        }
        if ($type == 2) {
            if ($status == 0) {
                $data1['msg'] = '接口无数据';
            } else {
                $data1['msg'] = '记录每日销售额';
                $data1['createtime'] = time();
                $data1['updatetime'] = time();
                $data1['type'] = 2;
                $data1['accounturl'] = $data['accounturl'];
                $data1['day'] = $data['day'];
                $data1['sum'] = $data['sum'];
                $return = table('fedition_logshopify')->insert($data1, true);
            }
        }
        if ($type == 3) {
            $data1['msg'] = '订单更新';
            $data1['createtime'] = time();
            $data1['updatetime'] = time();
            $data1['type'] = 3;
            $data1['accounturl'] = $data['accounturl'];
            $data1['day'] = date('Y-m-d', $data['created_at']);
            $data1['sum'] = $data['total_price'];
            $return = table('fedition_logshopify')->insert($data1, true);
        }
        return true;
    }

    /**
     * add_freight 新增费用
     * istransfer
     * 0未对接
     * 1对接成功
     * 2对接失败
     * 3未找到该订单
     */
    public function addfreight($id = null)
    {
        if (!empty($id)) {
            $ordershopify = table('fedition_ordershopify')->where('id', $id)->select();
        } else {
            $type = $this->request->request('type');

            //加入只操作上个月的限制
            //            $where_created = array();
            //            $created_star = '1630425600';
            //            $created_end = '1633017599';
            //            $where_created['created_at'] = array(array('egt',$created_star),array('elt',$created_end));

            $ordershopify = table('fedition_ordershopify')
                ->where('istransfer', $type)
                //                ->where($where_created)
                ->order('transfertime asc')
                ->limit(50)->select();
        }
        if (!empty($ordershopify)) {
            foreach ($ordershopify as $item) {
                $shopify = $this->add_freight($item);
            }
            $this->success('操作成功', $shopify);
        } else {
            $this->error('未找到相关订单');
        }
    }

    public function add_freight($ordershopify)
    {
        $ordertransfer = table('fedition_ordertransfer')->where('transfer_number', $ordershopify['tracking_number'])->find();
        $data['transfertime'] = time();
        if (!empty($ordertransfer)) {
            $data['freight'] = $ordertransfer['freight'];
            $data['freightmj'] = (float)number_format((float)$data['freight'] / 6.453, 3, '.', '');
            $data['istransfer'] = 1;
        } else {
            $data['istransfer'] = 3;
        }
        if ($ordershopify['istransfer'] == 5) {
            $data['istransfer'] = 1;
        }
        $shopify = table('fedition_ordershopify')->where('id', $ordershopify['id'])->update($data);
        return $shopify;
    }

    /**
     * 新增采购成本
     */
    public function addmaterial($id = null)
    {
        if (!empty($id)) {
            $ordershopify = table('fedition_ordershopify')->where('id', $id)->select();
        } else {
            $type = $this->request->request('type');

            //加入只操作上个月的限制
            //            $where_created = array();
            //            $created_star = '1630425600';
            //            $created_end = '1633017599';
            //            $where_created['created_at'] = array(array('egt',$created_star),array('elt',$created_end));

            //从56店铺开始更新
            $where['accounturl']  = array('egt', 56);
            $where['created_at']  = array('egt', 1656604800);
            $ordershopify = table('fedition_ordershopify')
                ->where('ismaterial', $type)
                ->where($where)
                //                ->where($where_created)
                ->order('materialtime asc')
                ->limit(200)->select();
        }
        if (!empty($ordershopify)) {
            foreach ($ordershopify as $item) {
                $shopify = $this->add_material($item);
            }
            $this->success('操作成功', $shopify);
        } else {
            $this->error('未找到相关订单');
        }
    }

    public function add_material($ordershopify)
    {
        $orderquantity = table('fedition_orderquantity')->where('order_id', $ordershopify['id'])->select();
        $material = 0;
        if (!empty($orderquantity)) {
            foreach ($orderquantity as $item) {
                $ordersku = table('fedition_ordersku')
                    ->where('variants_id', $item['variant_id'])
                    ->find();
                if (!empty($ordersku['sku']) && isset($ordersku['sku'])) {
                    if ($ordersku['sku'] == '2022国旗卷' || $ordersku['sku'] == '2022国旗卷-5' || $ordersku['sku'] == '2022国旗卷-10' || $ordersku['sku'] == '2022国旗卷-3') {
                        if ($item['quantity'] > 1) {
                            if ($ordersku['sku'] == '2022国旗卷') {
                                $quantity1 = $item['quantity'] - 1;
                                $newmaterial = $ordersku['material'] + $quantity1 * 10 / 7.150;
                            } else if ($ordersku['sku'] == '2022国旗卷-3') {
                                $quantity1 = $item['quantity'] * 3 - 1;
                                $newmaterial = $ordersku['material'] + $quantity1 * 10 / 7.150;
                            } else if ($ordersku['sku'] == '2022国旗卷-5') {
                                $quantity1 = $item['quantity'] * 5 - 1;
                                $newmaterial = $ordersku['material'] + $quantity1 * 10 / 7.150;
                            } else if ($ordersku['sku'] == '2022国旗卷-10') {
                                $quantity1 = $item['quantity'] * 10 - 1;
                                $newmaterial = $ordersku['material'] + $quantity1 * 10 / 7.150;
                            }
                            $material = $material + $newmaterial;
                        } else {
                            $material = $material + $ordersku['material'];
                        }
                    } else {
                        if (!empty($ordersku)) {
                            $newmaterial = $ordersku['material'] * $item['quantity'];
                            $material = $material + $newmaterial;
                        }
                    }
                } else {
                    if (!empty($ordersku)) {
                        $newmaterial = $ordersku['material'] * $item['quantity'];
                        $material = $material + $newmaterial;
                    }
                }
            }
        }
        $data['material'] = $material;
        $data['materialtime'] = time();
        if (!empty($data['material'])) {
            $data['ismaterial'] = 1;
        } else {
            $data['ismaterial'] = 3;
        }
        $shopify = table('fedition_ordershopify')->where('id', $ordershopify['id'])->update($data);
        return $shopify;
    }

    /**
     * orderproduct 新增商品对应的sku列表
     * read_products权限
     * read_inventory权限要开通
     */
    public function addorderproduct($product_id = null)
    {
        if (!empty($product_id)) {
            $orderproduct = table('fedition_orderproduct')->where('product_id', $product_id)->order('producttime asc')->select();
        } else {
            $type = $this->request->request('type');

            //从56店铺开始更新
            $where['accounturl']  = array('egt', 56);
            // $where['createtime']  = array('egt', 1656604800);

            $orderproduct = table('fedition_orderproduct')
                ->where($where)
                // ->where('isproduct',$type)
                ->where('product_id', '>', '0')
                ->order('producttime asc')
                ->limit(2)->select();
        }
        if (!empty($orderproduct)) {
            foreach ($orderproduct as $item) {
                $shopify[] = $this->add_orderproduct($item);
            }
            // $this->feditionorderquantity2();
            $this->success('操作成功', $shopify);
        } else {
            if (empty($product_id)) {
                //            未找到相关订单
                $this->error('未找到相关订单');
            }
        }
    }

    public function add_orderproduct($ordershopify)
    {
        $accounturl = table('fedition_accounturl')->where('id', $ordershopify['accounturl'])->find();
        $url = $accounturl['shopifyname'] . "/admin/api/2021-07/products/" . $ordershopify['product_id'] . "/variants.json";
        $data = $this->geturl($url, $accounturl['shopifyapikey'], $accounturl['shopifysecretapikey']);
        $arr['errors'] = '';
        if ($data) {
            $data = json_decode($data, true);
            if (!empty($data['errors'])) {
                $arr['isproduct'] = 3;
                $arr['errors'] = $data['errors'];
            } else {
                if (!empty($data['variants'])) {
                    $variantid = array();
                    foreach ($data['variants'] as $variant) {
                        $variantid[] = $variant['id'];
                        $inventory_item_id[] = $variant['inventory_item_id'];
                    }
                    if (!empty($inventory_item_id)) {
                        $inventory_item_id = implode(',', $inventory_item_id);
                        $urlp = $accounturl['shopifyname'] . "/admin/api/2021-07/inventory_items.json?ids=" . $inventory_item_id;
                        $datap = $this->geturl($urlp, $accounturl['shopifyapikey'], $accounturl['shopifysecretapikey']);
                        if ($datap) {
                            $datap = json_decode($datap, true);
                            if (!empty($datap['errors'])) {
                                $arr['errors'] = $datap['errors'];
                            }
                            if (!empty($datap['inventory_items'])) {
                                $arr['isproduct'] = 2;
                                foreach ($datap['inventory_items'] as $k => $variant) {
                                    $arr_product['variants_id'] = $variantid[$k];
                                    $arr_product['sku'] = $variant['sku'];
                                    //                                    if (empty($variant['cost'])) {
                                    //                                        if (!empty($data['variants'][$k]['price']) && isset($data['variants'][$k]['price'])) {
                                    //                                            $arr_product['material'] = $data['variants'][$k]['price'];
                                    //                                        }
                                    //                                    } else {
                                    $arr_product['material'] = $variant['cost'];
                                    //                                    }
                                    $arr_product['accounturl'] = $accounturl['id'];
                                    $arr_product['product_id'] = $ordershopify['product_id'];
                                    if (!empty($arr_product['variants_id'])) {
                                        $ordersku = table('fedition_ordersku')
                                            ->where('variants_id', $arr_product['variants_id'])
                                            ->find();
                                    } else {
                                        $ordersku = array();
                                    }
                                    if (empty($ordersku)) {
                                        $arr_product['createtime'] = time();
                                        $arr_product['updatetime'] = time();
                                        $succordersku = table('fedition_ordersku')->insert($arr_product);
                                        if (!empty($succordersku)) {
                                            $arr['isproduct'] = 1;
                                        }
                                    } else {
                                        if (empty($arr_product['material'])) {
                                            unset($arr_product['material']);
                                        }
                                        $arr_product['updatetime'] = time();
                                        $succordersku = table('fedition_ordersku')->where('variants_id', $arr_product['variants_id'])->update($arr_product);
                                        $arr['isproduct'] = 1;
                                    }
                                }
                            }
                        }
                    }
                } else {
                    $arr['isproduct'] = 4; //无属性
                }
            }
        } else {
            $arr['isproduct'] = 3;
        }
        $arr['producttime'] = time();
        $shopify = table('fedition_orderproduct')->where('id', $ordershopify['id'])->update($arr);
        return $shopify;
    }

    //    public function orderquantity_zmaterial()
    //    {
    //        $fedition_orderquantity = table('fedition_orderquantity')
    //            ->where('order_time','>',1)
    //            ->order('updatetime asc')
    //            ->limit(500)
    //            ->select();
    //        foreach ($fedition_orderquantity as $k=>$v) {
    //            if (!empty($v['variant_id'])) {
    //                $fedition_ordersku = table('fedition_ordersku')->where('variants_id',$v['variant_id'])->find();
    //                if (!empty($fedition_ordersku)) {
    //                    $arr['zmaterial'] = $v['quantity'] * $fedition_ordersku['material'];
    //                    $arr['updatetime'] = time();
    //                    table('fedition_orderquantity')->update($arr);
    //                }
    //            }
    //        }
    //    }

    /**
     * orderproduct 新增商品对应的sku列表
     */
    public function freightmj()
    {
        $ordershopify = table('fedition_ordershopify')
            ->select();
        if (!empty($ordershopify)) {
            foreach ($ordershopify as $item) {
                //人名币换算美金
                //                1美元=6.453元
                if (!empty($item['freight'])) {
                    $arr['freightmj'] = (float)number_format((float)$item['freight'] / 6.453, 3, '.', '');
                } else {
                    $arr['freightmj'] = $item['freightmj'];
                }
                $shopify = table('fedition_ordershopify')->where('id', $item['id'])->update($arr);
            }
            $this->success('操作成功', $shopify);
        } else {
            $this->error('未找到相关订单');
        }
    }

    /**
     * add_reportmonth 统计上个月利润
     * $type 1 上个月
     * 2 上上个月
     * 3 指定时间戳月份 传开始时间戳
     */
    public function add_reportmonth($id = null)
    {
        $where2 = '1=1';
        $timedate = 'created_at';
        if (!empty($id)) {
            $reportmonth = table('fedition_reportmonth')->where('id', $id)->find();
            if (!empty($reportmonth)) {
                $where2 = " accounturl = '" . $reportmonth['accounturl'] . "' ";
                $lastmonth_start = $reportmonth['timedate'];
                $lastmonth_end = mktime(23, 59, 59, date('m', $reportmonth['timedate']), date('t', $reportmonth['timedate']), date('Y', $reportmonth['timedate']));
            } else {
                $this->error('参数错误，请重新登录');
            }
        } else {
            if ($type == 1) {
                $lastmonth_start = mktime(0, 0, 0, date('m') - 1, 1, date('Y'));
                $lastmonth_end = mktime(23, 59, 59, date('m'), 0, date('Y'));
            } elseif ($type == 2) {
                $lastmonth_start = mktime(0, 0, 0, date('m') - 2, 1, date('Y'));
                $lastmonth_end = mktime(23, 59, 59, date('m') - 1, 0, date('Y'));
            } else {
                $lastmonth_start = mktime(0, 0, 0, date('m') - 1, 1, date('Y'));
                $lastmonth_end = mktime(23, 59, 59, date('m'), 0, date('Y'));
            }
        }

        $times = $timedate . '>=' . $lastmonth_start . ' and ' . $timedate . '<=' . $lastmonth_end;
        $sql = "SELECT accounturl
,cast(sum(total_price) AS decimal(15,2)) as total_price
,cast(sum(freight) AS decimal(15,2)) as freight
,cast(sum(freightmj) AS decimal(15,2)) as freightmj
,cast(sum(material) AS decimal(15,2)) as material
,cast(sum(total_tip_received) AS decimal(15,2)) as total_tip_received
FROM fa_fedition_ordershopify
WHERE " . $times . "
AND " . $where2 . "
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
GROUP BY accounturl
ORDER BY accounturl ASC";
        $statistics = \think\Db::query($sql);
        $reportmonth = array();
        foreach ($statistics as $item) {
            $arr['createtime'] = time();
            $arr['updatetime'] = time();
            $arr['freight'] = $item['freight'];
            $arr['freightmj'] = $item['freightmj'];
            $arr['material'] = $item['material'];
            $arr['total_tip_received'] = $item['total_tip_received'];

            $arr['zcost'] = $arr['material'] + $arr['freightmj'];
            //计算个人填写的广告消耗
            $accounturl = table('fedition_accounturl')->where('id', $item['accounturl'])->find();
            //            $admin_id = $accounturl['admin_id'];
            $arr['admin_id'] = $accounturl['admin_id'];
            //            $timedate = 'createtime';
            //            $wheretime2 = $timedate.'>='.$lastmonth_start.' and '.$timedate.'<='.$lastmonth_end;
            //            $wheres = 'and type = 1 and admin_id = '.$admin_id.' GROUP BY admin_id';
            //            $sqlreport = "SELECT
            //SUM(amount) as advertisingz,admin_id
            //FROM fa_advertising_report
            //WHERE ".$wheretime2." ".$wheres;
            //            $report = \think\Db::query($sqlreport);
            //            if (!empty($report) && isset($report[0]['advertisingz'])) {
            //                $arr['advertisingz'] = $report[0]['advertisingz'];
            //            } else {
            $arr['advertisingz'] = 0;
            //            }
            //一个店铺对应一个运营的情况
            //当一个店铺多个运营使用时则要新增其他方式
            $arr['saleszy'] = 0;
            $arr['salesz'] = 0;
            $arr['salesz_discount'] = 0;

            //原销售额 = 销售额 + 小费
            $arr['saleszy'] = $arr['total_tip_received'] + $item['total_price'];
            switch ($accounturl['currency']) {
                case 'USD':
                    $arr['salesz'] = $arr['saleszy'];
                    break;
                case 'EUR':
                    $arr['salesz'] = $arr['saleszy'] * 1.0615; //1欧元=1.0615美元
                    break;
                default:
                    $arr['salesz'] = $arr['saleszy'];
            }
            $arr['salesz_discount'] = $arr['salesz'] * 0.95;

            //total_price如果跟salesz不一样 是因为没有更新销售额接口
            //            http://121.5.76.151:100/api/Myshopify/savesales?type=1
            //            利润 = 销售总金额 - 广告消耗 -运费（美金） - 采购成本（美金）
            $arr['zcost'] = $arr['zcost'] + $arr['advertisingz'];
            $arr['gross_profit'] = $arr['salesz_discount'] - $arr['zcost'];
            $arr['timedate'] = $lastmonth_start;
            $arr['total_price'] = $item['total_price'];
            $arr['accounturl'] = $item['accounturl'];
            $account = table('fedition_reportmonth')
                ->where('timedate', $arr['timedate'])
                ->where('accounturl', $arr['accounturl'])
                ->find();
            if (empty($account)) {
                $reportmonth = table('fedition_reportmonth')->insert($arr);
            } else {
                $reportmonth = table('fedition_reportmonth')
                    ->where('timedate', $arr['timedate'])
                    ->where('accounturl', $arr['accounturl'])
                    ->update($arr);
            }
        }

        if (!empty($reportmonth)) {
            $this->success('操作成功', $reportmonth);
        } else {
            $this->error('未找到相关订单');
        }
    }

    //更新sku
    public function add_reportmonth_excel4()
    {
        $zyeji_sku = table('zyeji_info')
            ->where('status', 'hidden')
            // ->limit('200')
            ->order('updatetime asc')
            ->select();
        foreach ($zyeji_sku as $k => $v) {
            if (!empty($v['variants_id'])) {
                $update['material'] = $v['material'];
                $update['num'] = $v['num'];
                table('fedition_ordersku')
                    ->where('variants_id', $v['variants_id'])
                    ->update($update);
            } else {
                if (!empty($v['product_id'])) {
                    $orderskus = table('fedition_ordersku')
                        ->where('product_id', $v['product_id'])
                        ->where('sku', $v['sku'])
                        ->find();
                    if (!empty($orderskus)) {
                        $update['material'] = $v['material'];
                        $update['num'] = $v['num'];
                        table('fedition_ordersku')
                            ->where('product_id', $v['product_id'])
                            ->where('sku', $v['sku'])
                            ->update($update);
                    } else {
                        $update['material'] = $v['material'];
                        $update['num'] = $v['num'];
                        table('fedition_ordersku')
                            ->where('product_id', $v['product_id'])
                            ->update($update);
                    }
                }
            }
            $update2['updatetime'] = time();
            $update2['status'] = 'normal';
            table('zyeji_info')
                ->where('id', $v['id'])
                ->update($update2);
        }
        $this->success('操作成功');
    }

    //更新sku
    public function add_reportmonth_excel3()
    {
        //     $zyeji_sku = table('zyeji_sku')
        //         ->where('updatetime','<','223')
        //         ->order('updatetime asc')
        //         ->limit('200')
        //         ->select();
        //     foreach ($zyeji_sku as $k=>$v) {
        //         $update['material'] = $v['material'];
        //         $update['status'] = 'normal';
        //         $orderquantity = table('zyeji_info')
        //         ->where('title',$v['title'])
        //         // ->where('sku',$v['sku'])
        //         ->where('user',$v['admin'])
        //         ->find();

        //         if(!empty($orderquantity)){
        //             table('zyeji_info')
        //                 ->where('title',$v['title'])
        //                 // ->where('sku',$v['sku'])
        //                 ->where('user',$v['admin'])
        //                 ->update($update);
        //             $update2['updatetime'] = time();
        //         }else{
        //             $update2['updatetime'] = '222';
        //         }
        //         table('zyeji_sku')->where('id',$v['id'])->update($update2);
        //     }
        //     $this->success('操作成功');  
    }
    //个人业绩
    public function add_reportmonth_excelb()
    {
        $zyeji = table('zyejib')
            ->limit(1000)
            ->where('status', 'hidden')
            ->order('updatetime asc')
            ->select();
        $new = array();
        if (!empty($zyeji)) {
            foreach ($zyeji as $k => $v) {
                $fedition_ordershopify = table('fedition_ordershopify')
                    ->where('tracking_number', $v['tracking_number'])
                    ->where('name', $v['name'])
                    ->find();
                if (!empty($fedition_ordershopify)) {
                    $orderquantity = table('fedition_orderquantity')
                        ->field("a.*,b.material,b.num")
                        ->alias('a')
                        ->join('fa_fedition_ordersku b', 'b.variants_id = a.variant_id', 'left')
                        // ->join('fa_fedition_orderproduct c', 'c.product_id = a.product_id','left')
                        ->where('order_id', $fedition_ordershopify['id'])
                        ->select();
                    if (!empty($orderquantity)) {
                        foreach ($orderquantity as $ko => $vo) {
                            if (!empty($vo['quantity']) && isset($vo['quantity'])) {
                                if (!empty($new[$vo['product_id']]) && isset($new[$vo['product_id']])) {
                                    $new[$vo['product_id']]['quantity'] += $vo['quantity'];
                                } else {
                                    $new[$vo['product_id']]['quantity'] = $vo['quantity'];
                                }
                                $new[$vo['product_id']]['sku'] = $vo['sku'];
                                $new[$vo['product_id']]['title'] = $vo['title'];
                                $new[$vo['product_id']]['material'] = $vo['material'];
                                $new[$vo['product_id']]['num'] = $vo['num'];

                                $new[$vo['product_id']]['timedate'] = $v['timedate'];
                                $new[$vo['product_id']]['user'] = $v['user'];
                                $new[$vo['product_id']]['variants_id'] = $v['variants_id'];
                            }
                        }
                    }
                }
                $update['updatetime'] = time();
                $update['status'] = 'normal';
                $zyeji = table('zyejib')
                    ->where('id', $v['id'])
                    ->update($update);
            }
        }
        $res = array();
        if (!empty($new)) {
            foreach ($new as $ka => $va) {
                $zyeji_info = table('zyeji_infob')
                    ->where('timedate', $va['timedate'])
                    ->where('user', $va['user'])
                    ->where('product_id', $ka)
                    ->find();
                if (!empty($zyeji_info)) {
                    $update2['quantity'] = $zyeji_info['quantity'] + $va['quantity'];
                    $res[] = table('zyeji_infob')->where('product_id', $ka)->update($update2);
                } else {
                    $va['product_id'] = $ka;
                    $res[] = table('zyeji_infob')->insert($va);
                }
            }
        }
        $this->success('操作成功', $res);
    }

    public function add_reportmonth_excel2()
    {
        $zyeji = table('zyeji')
            ->limit(200)
            ->where('status', 'hidden')
            ->where('notestatus', 'normal')
            ->order('updatetime asc')
            ->select();
        $new = array();
        if (!empty($zyeji)) {
            foreach ($zyeji as $k => $v) {
                $fedition_ordershopify = table('fedition_ordershopify')
                    ->where('tracking_number', $v['tracking_number'])
                    ->where('name', $v['name'])
                    ->find();
                if (!empty($fedition_ordershopify)) {
                    $orderquantity = table('fedition_orderquantity')
                        ->field("a.*,b.material")
                        ->alias('a')
                        ->join('fa_fedition_ordersku b', 'b.variants_id = a.variant_id', 'left')
                        // ->join('fa_fedition_orderproduct c', 'c.product_id = a.product_id','left')
                        ->where('order_id', $fedition_ordershopify['id'])
                        ->select();
                    if (!empty($orderquantity)) {
                        foreach ($orderquantity as $ko => $vo) {
                            if (!empty($vo['quantity']) && isset($vo['quantity'])) {
                                if (!empty($new[$vo['product_id']]) && isset($new[$vo['product_id']])) {
                                    $new[$vo['product_id']]['quantity'] += $vo['quantity'];
                                } else {
                                    $new[$vo['product_id']]['quantity'] = $vo['quantity'];
                                }
                                $new[$vo['product_id']]['sku'] = $vo['sku'];
                                $new[$vo['product_id']]['title'] = $vo['title'];
                                $new[$vo['product_id']]['material'] = $vo['material'];

                                $new[$vo['product_id']]['timedate'] = $v['timedate'];
                                $new[$vo['product_id']]['user'] = $v['user'];
                                $new[$vo['product_id']]['variants_id'] = $vo['variant_id'];
                            }
                        }
                    }
                }
                $update['updatetime'] = time();
                $update['status'] = 'normal';
                $zyeji = table('zyeji')
                    ->where('id', $v['id'])
                    ->update($update);
            }
        }
        $res = array();
        if (!empty($new)) {

            foreach ($new as $ka => $va) {
                $zyeji_info = table('zyeji_info')
                    ->where('timedate', $va['timedate'])
                    ->where('user', $va['user'])
                    ->where('product_id', $ka)
                    ->find();
                if (!empty($zyeji_info)) {
                    $update2['quantity'] = $zyeji_info['quantity'] + $va['quantity'];
                    $res[] = table('zyeji_info')->where('product_id', $ka)->update($update2);
                } else {
                    $va['product_id'] = $ka;
                    $res[] = table('zyeji_info')->insert($va);
                }
            }
        }
        $this->success('操作成功', $res);
    }
    //个人业绩
    // user = 1 六月张书凡黄彬共有
    // user = 2 六月张书凡李娟共有
    public function add_reportmonth_excel($id = null)
    {
        $where2 = '1=1';
        $timedate = 'created_at';
        if (empty($id)) {
            $id = $this->request->request('id');
        }
        $reportmonthtwo = table('fedition_reportmonthtwo')->where('id', $id)->find();
        if (!empty($reportmonthtwo['admin_id'])) {
            $admin = table('admin')->where('id', $reportmonthtwo['admin_id'])->find();
            date_default_timezone_set('Asia/Shanghai');
            $lastmonth_start = $reportmonthtwo['timedate'];
            $firstday = date("Y-m-d", $lastmonth_start);
            $lastmonth_end = strtotime(date("Y-m-d", strtotime("$firstday +1 month")));
            $times = $timedate . '>=' . $lastmonth_start . ' and ' . $timedate . '<=' . $lastmonth_end;
        }
        $biexi = array();
        if (!empty($admin)) {
            table('zyeji')
                ->where('timedate', $lastmonth_start)
                ->where('user', $admin['id'])
                ->delete();
            table('zyeji_info')
                ->where('timedate', $lastmonth_start)
                ->where('user', $admin['id'])
                ->delete();
            table('zyeji_date')
                ->where('timedate', $lastmonth_start)
                ->where('user', $admin['id'])
                ->delete();
            table('zyejib')
                ->where('timedate', $lastmonth_start)
                ->delete();
            table('zyeji_infob')
                ->where('timedate', $lastmonth_start)
                ->delete();

            $accounturlgroup = table('fedition_accounturlgroup')
                ->field("c.*,tc.admin_type,tc.name as accounturl_name,tc.currency as currency")
                ->alias('c')
                ->join('fa_fedition_accounturl tc', 'c.accounturl = tc.id', 'left')
                ->where(
                    [
                        'c.admin_id' => $admin['id'],
                        'tc.admin_type' => 2,
                        'c.status' => 'normal'
                    ]
                )
                ->select();
            if (!empty($accounturlgroup)) {
                //                没到期的店铺
                $item1 = array();
                $item2 = array();
                $item3 = array();
                foreach ($accounturlgroup as $vgroup) {
                    if (empty($vgroup)) {
                    } else {
                        $lastmonth_start2 = $lastmonth_start;
                        $lastmonth_end2 = $lastmonth_end;
                        if ($vgroup['createtime'] > $lastmonth_start2) {
                            $lastmonth_start2 = $vgroup['createtime'];
                        }
                        if ($vgroup['updatetime'] < $lastmonth_end2) {
                            $lastmonth_end2 = $vgroup['updatetime'];
                        }
                        if ($lastmonth_start2 < $lastmonth_end2) {
                            //这个月有业绩
                            $timedate = 'created_at';
                            $times = $timedate . '>=' . $lastmonth_start2 . ' and ' . $timedate . '<=' . $lastmonth_end2;
                            $sql = "SELECT a.name,a.ycreated_at,a.total_price,a.freight,a.tracking_number,a.material,a.currency,a.tags,a.accounturl,a.created_at,a.total_tip_received,a.financial_status,a.fulfillment_status,a.total_shipping_price_set,a.current_subtotal_price
                            ,c.name as accounturl_name
            FROM fa_fedition_ordershopify as a
            LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
WHERE " . $times . "
AND " . $where2 . "
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
AND accounturl = " . $vgroup['accounturl'] . "
ORDER BY accounturl DESC,updated_at DESC,financial_status DESC";
                            $statistics = \think\Db::query($sql);
                            if (!empty($statistics)) {
                                $statisticsn1 = array();
                                foreach ($statistics as $k1 => $v1) {
                                    //去掉争议订单
                                    if (!empty($v1['tags']) && strpos($v1['tags'], 'dispute') !== false) {
                                        //争议订单
                                        $v1['notestatus'] = 'hidden';
                                    } elseif (!empty($v2['tags']) && strpos($v2['tags'], 'Dispute') !== false) {
                                        //争议订单
                                        $v2['notestatus'] = 'hidden';
                                    } else {
                                        $v1['notestatus'] = 'normal';
                                    }
                                    $v1['timedate'] = $lastmonth_start;
                                    $v1['user'] = $admin['id'];


                                    //去掉特殊订单
                                    // 8.28-9.05 01 02店铺不算业绩
                                    if ($v1['accounturl'] == '57' || $v1['accounturl'] == '59') {
                                        if ($v1['created_at'] >= '1661616000' && $v1['created_at'] <= '1662393599') {
                                            $v1['notestatus'] = 'abnormal';
                                        }
                                    }

                                    //biexi
                                    if ($v1['accounturl'] == '56' && $admin['id'] == '33' && $v1['created_at'] >= '1661961600') {
                                        if (!empty($v1['tags']) && strpos($v1['tags'], 'outbrain') !== false) {
                                            //别昕
                                            $v2 = $v1;
                                            // unset($v2['tags']);
                                            $v2['user'] = '37';
                                            if ($v2['notestatus'] == 'normal') {
                                                if ($v2['created_at'] <= '1663516800') {
                                                    $v2['notestatus'] = 'hidden';
                                                }
                                                unset($v2['accounturl']);
                                                $biexi[] = $v2;
                                            }
                                            $v1['notestatus'] = 'hidden';
                                        }
                                    }

                                    //新增日期
                                    $v1['date_of'] = date("Y-m-d", $v1['created_at']);
                                    unset($v1['accounturl']);

                                    // unset($v1['tags']);
                                    $statisticsn1[] = $v1;
                                }
                                if (!empty($biexi)) {
                                    table('zyeji')->insertAll($biexi);
                                }

                                table('zyeji')->insertAll($statisticsn1);
                            }
                        }
                    }
                }
            }
            //固定店铺的业绩
            //按标签分类的店铺
            $times = $timedate . '>=' . $lastmonth_start . ' and ' . $timedate . '<=' . $lastmonth_end;
            switch ($admin['id']) {
                case '26':
                    $tags = 'zsf';
                    break;
                case '27':
                    $tags = 'HB';
                    break;
                case '29':
                    $tags = 'ZY';
                    break;
                case '30':
                    $tags = 'aohui';
                    break;
                case '33':
                    $tags = 'CY';
                    break;
                case '35':
                    $tags = 'lj';
                    break;
                default:
                    $tags = 'nobady';
            }
            if ($tags == 'nobady') {
                $statistics2 = array();
            } else {
                $wheretag = "user_id like '%" . $tags . "%'";
                $sql2 = "SELECT a.name,a.ycreated_at,a.total_price,a.freight,a.tracking_number,a.material,a.currency,a.tags,a.accounturl,a.created_at
                ,c.name as accounturl_name,a.total_tip_received,a.financial_status,a.fulfillment_status,a.total_shipping_price_set,a.current_subtotal_price
FROM fa_fedition_ordershopify as a
LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
WHERE " . $wheretag . "
AND " . $times . "
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
AND admin_type = 1
ORDER BY accounturl DESC,updated_at DESC,financial_status DESC";
                $statistics2 = \think\Db::query($sql2);
            }
            if (!empty($statistics2)) {
                $statistics2n = array();
                foreach ($statistics2 as $k2 => $v2) {
                    //去掉争议订单
                    if (!empty($v2['tags']) && strpos($v2['tags'], 'dispute') !== false) {
                        //争议订单
                        $v2['notestatus'] = 'hidden';
                    } elseif (!empty($v2['tags']) && strpos($v2['tags'], 'Dispute') !== false) {
                        //争议订单
                        $v2['notestatus'] = 'hidden';
                    } else {
                        $v2['notestatus'] = 'normal';
                    }
                    $v2['timedate'] = $lastmonth_start;
                    $v2['user'] = $admin['id'];
                    // unset($v2['tags']);

                    //去掉特殊订单
                    // 8.28-9.05 01 02店铺不算业绩
                    if ($v2['accounturl'] == '57' || $v2['accounturl'] == '59') {
                        if ($v2['created_at'] >= '1661616000' && $v2['created_at'] <= '1662393599') {
                            $v2['notestatus'] = 'abnormal';
                        }
                    }

                    $v2['date_of'] = date("Y-m-d", $v2['created_at']);
                    unset($v2['accounturl']);

                    $statistics2n[] = $v2;
                }
                table('zyeji')->insertAll($statistics2n);
            }

            //五月份特殊情况
            //             if ($reportmonthtwo['timedate'] == '1651334400') {
            //                 $sqlh = "SELECT a.name,a.ycreated_at,a.total_price,a.freight,a.tracking_number,a.material,a.currency
            //                 ,c.name as accounturl_name
            // FROM fa_fedition_ordershopify as a
            // LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
            // WHERE (user_id like '%zsf%' AND user_id like '%HB%')
            // AND created_at>=1651334400
            // AND created_at<=1654012800
            // AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
            // AND fulfillment_status = 'fulfilled'
            // AND accounturl = 57
            // ORDER BY accounturl DESC,updated_at DESC,financial_status DESC";
            //                 $statisticsh = \think\Db::query($sqlh);
            //                 if (!empty($statisticsh)) {
            //                     table('zyejib')->insertAll($statisticsh);
            //                 }
            //             }
            //五月份特殊情况结束
            // 六月份特殊情况
            if ($reportmonthtwo['timedate'] == '1659283200') {
                $sqlh = "SELECT a.name,a.ycreated_at,a.total_price,a.freight,a.tracking_number,a.material,a.currency
                ,c.name as accounturl_name
FROM fa_fedition_ordershopify as a
LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
WHERE (user_id like '%CY%' AND user_id like '%HB%')
AND created_at>=1659283200
AND created_at<=1661961600
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
AND accounturl = 57
ORDER BY accounturl DESC,updated_at DESC,financial_status DESC";
                $statisticsh = \think\Db::query($sqlh);
                if (!empty($statisticsh)) {
                    foreach ($statisticsh as $kh => $vh) {
                        $statisticsh[$kh]['timedate'] = $lastmonth_start;
                        $statisticsh[$kh]['user'] = '8月cy黄彬共有';
                    }
                    table('zyejib')->insertAll($statisticsh);
                }

                $sqlh2 = "SELECT a.name,a.ycreated_at,a.total_price,a.freight,a.tracking_number,a.material,a.currency
                ,c.name as accounturl_name
FROM fa_fedition_ordershopify as a
LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
WHERE (user_id like '%CY%' AND user_id like '%lj%')
AND created_at>=1659283200
AND created_at<=1661961600
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
AND accounturl = 57
ORDER BY accounturl DESC,updated_at DESC,financial_status DESC";
                $statisticsh2 = \think\Db::query($sqlh2);
                if (!empty($statisticsh2)) {
                    foreach ($statisticsh2 as $kh2 => $vh2) {
                        $statisticsh2[$kh2]['timedate'] = $lastmonth_start;
                        $statisticsh2[$kh2]['user'] = '8月cy李娟共有';
                    }
                    table('zyejib')->insertAll($statisticsh2);
                }

                $sqlh2 = "SELECT a.name,a.ycreated_at,a.total_price,a.freight,a.tracking_number,a.material,a.currency
                ,c.name as accounturl_name
FROM fa_fedition_ordershopify as a
LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
WHERE (user_id like '%lj%' AND user_id like '%HB%')
AND created_at>=1659283200
AND created_at<=1661961600
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
AND accounturl = 57
ORDER BY accounturl DESC,updated_at DESC,financial_status DESC";
                $statisticsh2 = \think\Db::query($sqlh2);
                if (!empty($statisticsh2)) {
                    foreach ($statisticsh2 as $kh2 => $vh2) {
                        $statisticsh2[$kh2]['timedate'] = $lastmonth_start;
                        $statisticsh2[$kh2]['user'] = '8月lj黄彬共有';
                    }
                    table('zyejib')->insertAll($statisticsh2);
                }
            }
            // 六月份特殊情况结束
            $v2['timedate'] = $lastmonth_start;
            $v2['user'] = $admin['id'];
            // 按天统计运营情况
            $this->days_statistical($lastmonth_start, $admin['id']);
        }
        return true;
    }

    // 按天统计运营情况
    public function days_statistical($timedate, $user)
    {

        $where['timedate'] = $timedate;
        $where['user'] = $user;
        $zyeji = table('zyeji')
            ->field("timedate,user,accounturl_name,date_of,currency,SUM(`total_price`) as total_price,SUM(`freight`) as freight,SUM(`material`) as material,SUM(`total_tip_received`) as total_tip_received,SUM(`total_shipping_price_set`) as total_shipping_price_set,SUM(`current_subtotal_price`) as current_subtotal_price,SUM(`order_num`) as order_num")
            ->where($where)
            ->group('accounturl_name,date_of')
            ->select();
        if (!empty($zyeji)) {
            table('zyeji_date')->insertAll($zyeji);
        }
    }

    public function add_reportmonthtwoy()
    {
        $thismonth = date('m');
        $thisyear = date('Y');
        if ($thismonth == 1) {
            $lastmonth = 11;
            $lastyear = $thisyear - 1;
        } elseif ($thismonth == 2) {
            $lastmonth = 12;
            $lastyear = $thisyear - 1;
        } else {
            $lastmonth = $thismonth - 2;
            $lastyear = $thisyear;
        }
        $lastStartDay = $lastyear . '-' . $lastmonth . '-1';
        $b_time = strtotime($lastStartDay); //上个月的月初时间戳
        $admins = table('admin')->where('launch', 1)->select();
        foreach ($admins as $ka => $va) {
            $reportmonthtwo = table('fedition_reportmonthtwo')
                ->where('admin_id', $va['id'])
                ->where('timedate', $b_time)
                ->find();
            if (empty($reportmonthtwo)) {
                $arr = array();
                $arr['timedate'] = $b_time;
                $arr['admin_id'] = $va['id'];
                $arr['createtime'] = time();
                $arr['updatetime'] = time();
                table('fedition_reportmonthtwo')->insert($arr);
            }
        }
        $this->success('操作成功');
    }
    //个人业绩
    public function add_reportmonthtwo($id = null)
    {

        $where2 = '1=1';
        $timedate = 'created_at';

        //计算个人业绩
        $reportmonthtwo = table('fedition_reportmonthtwo')->where('id', $id)->find();
        if (!empty($reportmonthtwo['admin_id'])) {
            $admin = table('admin')->where('id', $reportmonthtwo['admin_id'])->find();

            //            $lastmonth_start=mktime(0,0,0,date('m')-1,1,date('Y'));
            //            $lastmonth_end=mktime(23,59,59,date('m'),0,date('Y'));
            date_default_timezone_set('Asia/Shanghai');

            $lastmonth_start = $reportmonthtwo['timedate'];
            $firstday = date("Y-m-d", $lastmonth_start);
            $lastmonth_end = strtotime(date("Y-m-d", strtotime("$firstday +1 month")));

            $times = $timedate . '>=' . $lastmonth_start . ' and ' . $timedate . '<=' . $lastmonth_end;
        }
        $info = '';
        if (!empty($admin)) {
            //运营归属店铺的业绩
            $accounturlgroup = table('fedition_accounturlgroup')
                ->field("c.*,tc.admin_type,tc.name as accounturl_name,tc.currency as currency")
                ->alias('c')
                ->join('fa_fedition_accounturl tc', 'c.accounturl = tc.id', 'left')
                ->where(
                    [
                        'c.admin_id' => $admin['id'],
                        'tc.admin_type' => 2,
                        'c.status' => 'normal'
                    ]
                )
                ->select();
            $arr = array();

            //四月份特殊情况
            $gongtong4 = array();
            $gongtong5 = array();
            // 4.13到月底共有单
            if ($reportmonthtwo['timedate'] == '1648742400') {
                $sqlh = "SELECT cast(sum(total_price) AS decimal(15,2)) as total_price
,cast(sum(freight) AS decimal(15,2)) as freight
,cast(sum(freightmj) AS decimal(15,2)) as freightmj
,cast(sum(material) AS decimal(15,2)) as material
,count(countnum) as countnums
,c.name as accounturl_name
FROM fa_fedition_ordershopify as a
LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
WHERE (user_id like '%zsf%' AND user_id like '%HB%')
AND created_at>=1649779200
AND created_at<=1651334399
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
-- AND fulfillment_status = 'fulfilled'
AND accounturl = 57
ORDER BY accounturl ASC";
                $statisticsh = \think\Db::query($sqlh);
                if (!empty($statisticsh[0]['countnums'])) {
                    $gongtong4 = $statisticsh[0];
                }
            }
            //四月份特殊情况结束

            //五月份特殊情况
            if ($reportmonthtwo['timedate'] == '1651334400') {
                $sqlh = "SELECT cast(sum(total_price) AS decimal(15,2)) as total_price
,cast(sum(freight) AS decimal(15,2)) as freight
,cast(sum(freightmj) AS decimal(15,2)) as freightmj
,cast(sum(material) AS decimal(15,2)) as material
,count(countnum) as countnums
,c.name as accounturl_name
FROM fa_fedition_ordershopify as a
LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
WHERE (user_id like '%zsf%' AND user_id like '%HB%')
AND created_at>=1651334400
AND created_at<=1654012800
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
-- AND fulfillment_status = 'fulfilled'
AND accounturl = 57
ORDER BY accounturl ASC";
                $statisticsh = \think\Db::query($sqlh);
                if (!empty($statisticsh[0]['countnums'])) {
                    $gongtong5 = $statisticsh[0];
                }
            }
            //五月份特殊情况结束


            //九月份特殊情况
            if ($reportmonthtwo['timedate'] == '1661961600') {
                $sqlh = "SELECT cast(sum(total_price) AS decimal(15,2)) as total_price
,cast(sum(freight) AS decimal(15,2)) as freight
,cast(sum(freightmj) AS decimal(15,2)) as freightmj
,cast(sum(material) AS decimal(15,2)) as material
,count(countnum) as countnums
,c.name as accounturl_name
FROM fa_fedition_ordershopify as a
LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
WHERE tags='outbrain'
AND created_at>=1661961600
AND created_at<=1664553600
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
-- AND fulfillment_status = 'fulfilled'
AND accounturl = 56
ORDER BY accounturl ASC";
                $statisticsh = \think\Db::query($sqlh);
                if (!empty($statisticsh[0]['countnums'])) {
                    $gongtong9 = $statisticsh[0];
                }
            }
            //九月份特殊情况结束


            //十月份特殊情况
            if ($reportmonthtwo['timedate'] == '1664553600') {
                $sqlh = "SELECT cast(sum(total_price) AS decimal(15,2)) as total_price
,cast(sum(freight) AS decimal(15,2)) as freight
,cast(sum(freightmj) AS decimal(15,2)) as freightmj
,cast(sum(material) AS decimal(15,2)) as material
,count(countnum) as countnums
,c.name as accounturl_name
FROM fa_fedition_ordershopify as a
LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
WHERE tags='outbrain'
AND created_at>=1664553600
AND created_at<=1667232000
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
-- AND fulfillment_status = 'fulfilled'
AND accounturl = 56
ORDER BY accounturl ASC";
                $statisticsh = \think\Db::query($sqlh);
                if (!empty($statisticsh[0]['countnums'])) {
                    $gongtong9 = $statisticsh[0];
                }
            }
            //十月份特殊情况结束


            $arr['freight'] = 0;
            $arr['freightmj'] = 0;
            $arr['material'] = 0;
            $arr['total_price'] = 0;
            $arr['freightmj'] = 0;
            $arr['total_tip_received'] = 0;
            $arr['countnums'] = 0;
            $arr['saleszy'] = 0;
            $arr['salesz'] = 0;

            $arr2['freight'] = 0;
            $arr2['freightmj'] = 0;
            $arr2['material'] = 0;
            $arr2['total_price'] = 0;
            $arr2['freightmj'] = 0;
            $arr2['total_tip_received'] = 0;
            $arr2['countnums'] = 0;
            $arr2['saleszy'] = 0;
            $arr2['salesz'] = 0;

            if (!empty($accounturlgroup)) {
                //                没到期的店铺
                $saleszy = '';
                $salesz = '';
                $arr['countnumst'] = 0;
                $arr['countnumsz'] = 0;
                $arr['countnumsw'] = 0;

                foreach ($accounturlgroup as $vgroup) {
                    if (empty($vgroup)) {
                    } else {
                        $lastmonth_start2 = $lastmonth_start;
                        $lastmonth_end2 = $lastmonth_end;
                        if ($vgroup['createtime'] > $lastmonth_start2) {
                            $lastmonth_start2 = $vgroup['createtime'];
                        }
                        if ($vgroup['updatetime'] < $lastmonth_end2) {
                            $lastmonth_end2 = $vgroup['updatetime'];
                        }
                        if ($lastmonth_start2 < $lastmonth_end2) {
                            //这个月有业绩
                            $timedate = 'created_at';
                            $times = $timedate . '>=' . $lastmonth_start2 . ' and ' . $timedate . '<=' . $lastmonth_end2;
                            $sql = "SELECT accounturl
,cast(sum(total_price) AS decimal(15,2)) as total_price
,cast(sum(freight) AS decimal(15,2)) as freight
,cast(sum(freightmj) AS decimal(15,2)) as freightmj
,cast(sum(material) AS decimal(15,2)) as material
,cast(sum(total_tip_received) AS decimal(15,2)) as total_tip_received
,count(countnum) as countnums
FROM fa_fedition_ordershopify
WHERE " . $times . "
AND " . $where2 . "
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
AND accounturl = " . $vgroup['accounturl'] . "
ORDER BY accounturl ASC";
                            $statistics = \think\Db::query($sql);
                            if (!empty($statistics[0])) {
                                $item = $statistics[0];
                                if (!empty($arr['total_price'])) {
                                    $arr['total_price'] += $item['total_price'];
                                } else {
                                    $arr['total_price'] = $item['total_price'];
                                }
                                if (!empty($arr['freight'])) {
                                    $arr['freight'] += $item['freight'];
                                } else {
                                    $arr['freight'] = $item['freight'];
                                }
                                if (!empty($arr['freightmj'])) {
                                    $arr['freightmj'] += $item['freightmj'];
                                } else {
                                    $arr['freightmj'] = $item['freightmj'];
                                }
                                if (!empty($arr['material'])) {
                                    $arr['material'] += $item['material'];
                                } else {
                                    $arr['material'] = $item['material'];
                                }
                                if (!empty($arr['total_tip_received'])) {
                                    $arr['total_tip_received'] += $item['total_tip_received'];
                                } else {
                                    $arr['total_tip_received'] = $item['total_tip_received'];
                                }
                                if (!empty($arr['countnums'])) {
                                    $arr['countnums'] += $item['countnums'];
                                } else {
                                    $arr['countnums'] = $item['countnums'];
                                }

                                $saleszy = $item['total_tip_received'] + $item['total_price'];
                                switch ($vgroup['currency']) {
                                    case 'USD':
                                        $salesz = $saleszy;
                                        break;
                                    case 'EUR':
                                        $salesz = $saleszy * 1.0615; //1欧元=1.0615美元
                                        break;
                                    default:
                                        $salesz = $saleszy;
                                }
                                if (!empty($arr['saleszy'])) {
                                    $arr['saleszy'] += $saleszy;
                                } else {
                                    $arr['saleszy'] = $saleszy;
                                }
                                if (!empty($arr['salesz'])) {
                                    $arr['salesz'] += $salesz;
                                } else {
                                    $arr['salesz'] = $salesz;
                                }
                                if (!empty($salesz)) {
                                    //备注销售额来源
                                    $info = $info . "
                                " . $salesz . '(' . $vgroup['accounturl_name'] . ')';
                                }
                            }

                            //附加数量
                            $sqlt1 = "SELECT accounturl
,count(countnum) as countnumsz
FROM fa_fedition_ordershopify
WHERE " . $times . "
AND " . $where2 . "
AND accounturl = " . $vgroup['accounturl'] . "
ORDER BY accounturl ASC";
                            $statisticst1 = \think\Db::query($sqlt1);
                            if (!empty($statisticst1[0])) {
                                if (!empty($arr['countnumsz'])) {
                                    $arr['countnumsz'] += $statisticst1[0]['countnumsz'];
                                } else {
                                    $arr['countnumsz'] = $statisticst1[0]['countnumsz'];
                                }
                            }
                            $sqlt2 = "SELECT accounturl
,count(countnum) as countnumst
FROM fa_fedition_ordershopify
WHERE " . $times . "
AND " . $where2 . "
AND financial_status = 'refunded'
AND accounturl = " . $vgroup['accounturl'] . "
ORDER BY accounturl ASC";
                            $statisticst2 = \think\Db::query($sqlt2);
                            if (!empty($statisticst2[0])) {
                                if (!empty($arr['countnumst'])) {
                                    $arr['countnumst'] += $statisticst2[0]['countnumst'];
                                } else {
                                    $arr['countnumst'] = $statisticst2[0]['countnumst'];
                                }
                            }
                            $sqlt3 = "SELECT accounturl
,count(countnum) as countnumsw
FROM fa_fedition_ordershopify
WHERE " . $times . "
AND " . $where2 . "
AND (fulfillment_status = 'unfulfilled' or fulfillment_status = '' or fulfillment_status IS NULL)
AND accounturl = " . $vgroup['accounturl'] . "
ORDER BY accounturl ASC";
                            $statisticst3 = \think\Db::query($sqlt3);
                            if (!empty($statisticst3[0])) {
                                if (!empty($arr['countnumsw'])) {
                                    $arr['countnumsw'] += $statisticst3[0]['countnumsw'];
                                } else {
                                    $arr['countnumsw'] = $statisticst3[0]['countnumsw'];
                                }
                            }
                            //附加数量
                        }
                    }
                }
            }

            //固定店铺的业绩
            //按标签分类的店铺
            $times = $timedate . '>=' . $lastmonth_start . ' and ' . $timedate . '<=' . $lastmonth_end;
            switch ($admin['id']) {
                case '26':
                    $tags = 'zsf';
                    break;
                case '27':
                    $tags = 'HB';
                    break;
                case '29':
                    $tags = 'ZY';
                    break;
                case '30':
                    $tags = 'aohui';
                    break;
                case '33':
                    $tags = 'CY';
                    break;
                case '35':
                    $tags = 'lj';
                    break;
                case '37':
                    $tags = 'BX';
                    break;
                default:
                    $tags = 'nobady';
            }
            if ($tags == 'nobady') {
                $statistics2 = array();
            } else {
                //四月特殊情况
                // 黄彬计算4.13到月底
                if ($admin['id'] == '27' && $reportmonthtwo['timedate'] == '1648742400') {
                    $times = $timedate . '>=1649779200 and ' . $timedate . '<=1651334399';
                }
                // 成誉计算4.6到月底
                if ($admin['id'] == '33' && $reportmonthtwo['timedate'] == '1648742400') {
                    $times = $timedate . '>=1649174400 and ' . $timedate . '<=1651334399';
                }
                // $wheretag = "(user_id like '%".$admin['username']."%' OR user_id like '%".$tags."%')";
                $wheretag = "user_id like '%" . $tags . "%'";
                $sql2 = "SELECT cast(sum(total_price) AS decimal(15,2)) as total_price
,cast(sum(freight) AS decimal(15,2)) as freight
,cast(sum(freightmj) AS decimal(15,2)) as freightmj
,cast(sum(material) AS decimal(15,2)) as material
,cast(sum(total_tip_received) AS decimal(15,2)) as total_tip_received
,count(countnum) as countnums
,c.name as accounturl_name
,c.currency as currency
FROM fa_fedition_ordershopify as a
LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
WHERE " . $wheretag . "
AND " . $times . "
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
AND admin_type = 1
ORDER BY accounturl ASC";
                $statistics2 = \think\Db::query($sql2);
            }
            if (!empty($statistics2[0])) {
                $item2 = $statistics2[0];
                $arr2['freight'] = $item2['freight'];
                $arr2['freightmj'] = $item2['freightmj'];
                $arr2['material'] = $item2['material'];
                $arr2['total_tip_received'] = $item2['total_tip_received'];
                $arr2['total_price'] = $item2['total_price'];

                $arr2['saleszy'] = $arr2['total_tip_received'] + $arr2['total_price'];
                switch ($item2['currency']) {
                    case 'USD':
                        $arr2['salesz'] = $arr2['saleszy'];
                        break;
                    case 'EUR':
                        $arr2['salesz'] = $arr2['saleszy'] * 1.0615; //1欧元=1.0615美元
                        break;
                    default:
                        $arr2['salesz'] = $arr2['saleszy'];
                }

                if (!empty($arr2['total_price'])) {
                    //备注销售额来源
                    $info = $info . "
                                " . $arr2['salesz'] . '(' . $item2['accounturl_name'] . ')';
                }
                $arr2['countnums'] = $item2['countnums'];
            }

            $arr2['countnumsz'] = 0;
            $arr2['countnumst'] = 0;
            $arr2['countnumsw'] = 0;
            $wheretag = "user_id like '%" . $tags . "%'";
            //附加数量
            $sqly1 = "SELECT count(countnum) as countnumsz
            ,c.name as accounturl_name
            ,c.currency as currency
            FROM fa_fedition_ordershopify as a
            LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
            WHERE " . $wheretag . "
            AND " . $times . "
            AND admin_type = 1
            ORDER BY accounturl ASC";
            $statisticsy1 = \think\Db::query($sqly1);
            if (!empty($statisticsy1[0])) {
                $arr2['countnumsz'] = $statisticsy1[0]['countnumsz'];
            }
            $sqly2 = "SELECT count(countnum) as countnumst
            ,c.name as accounturl_name
            ,c.currency as currency
            FROM fa_fedition_ordershopify as a
            LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
            WHERE " . $wheretag . "
            AND " . $times . "
            AND financial_status = 'refunded'
            AND admin_type = 1
            ORDER BY accounturl ASC";
            $statisticsy2 = \think\Db::query($sqly2);
            if (!empty($statisticsy2[0])) {
                $arr2['countnumst'] = $statisticsy2[0]['countnumst'];
            }
            $sqly3 = "SELECT count(countnum) as countnumsw
            ,c.name as accounturl_name
            ,c.currency as currency
            FROM fa_fedition_ordershopify as a
            LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
            WHERE " . $wheretag . "
            AND " . $times . "
            AND (fulfillment_status = 'unfulfilled' or fulfillment_status = '' or fulfillment_status IS NULL)
            AND admin_type = 1
            ORDER BY accounturl ASC";
            $statisticsy3 = \think\Db::query($sqly3);
            if (!empty($statisticsy3[0])) {
                $arr2['countnumsw'] = $statisticsy3[0]['countnumsw'];
            }
            //附加数量

            if (!empty($arr2) && !empty($arr)) {
                $arr3['freight'] = $arr2['freight'] + $arr['freight'];
                $arr3['freightmj'] = $arr2['freightmj'] + $arr['freightmj'];
                $arr3['material'] = $arr2['material'] + $arr['material'];
                $arr3['total_price'] = $arr2['total_price'] + $arr['total_price'];
                $arr3['total_tip_received'] = $arr2['total_tip_received'] + $arr['total_tip_received'];
                $arr3['countnums'] = $arr2['countnums'] + $arr['countnums'];
                $arr3['saleszy'] = $arr2['saleszy'] + $arr['saleszy'];
                $arr3['salesz'] = $arr2['salesz'] + $arr['salesz'];
                $arr3['countnumsz'] = $arr2['countnumsz'] + $arr['countnumsz'];
                $arr3['countnumst'] = $arr2['countnumst'] + $arr['countnumst'];
                $arr3['countnumsw'] = $arr2['countnumsw'] + $arr['countnumsw'];
            } elseif (!empty($arr2) && empty($arr)) {
                $arr3 = $arr2;
            } elseif (empty($arr2) && !empty($arr)) {
                $arr3 = $arr;
            } else {
                $arr3 = array();
            }
            if (!empty($arr3) || $admin['id'] == '37') {
                //四月特殊情况
                if ($reportmonthtwo['timedate'] == '1648742400' && !empty($gongtong4)) {
                    if ($admin['id'] == '27' || $admin['id'] == '26') {
                        $arr3['total_price'] = $arr3['total_price'] - (float)number_format((float)$gongtong4['total_price'] / 2, 3, '.', '');
                        $arr3['freight'] = $arr3['freight'] - (float)number_format((float)$gongtong4['freight'] / 2, 3, '.', '');
                        $arr3['freightmj'] = $arr3['freightmj'] - (float)number_format((float)$gongtong4['freightmj'] / 2, 3, '.', '');
                        $arr3['material'] = $arr3['material'] - (float)number_format((float)$gongtong4['material'] / 2, 3, '.', '');
                        $info = $info . "
                            " . (float)number_format((float)$gongtong4['total_price'] / 2, 3, '.', '') . "(平分销售额)";
                    }
                }
                //四月特殊情况
                //五月特殊情况
                if ($reportmonthtwo['timedate'] == '1651334400' && !empty($gongtong5)) {
                    if ($admin['id'] == '27' || $admin['id'] == '26') {
                        $arr3['total_price'] = $arr3['total_price'] - (float)number_format((float)$gongtong5['total_price'] / 2, 3, '.', '');
                        $arr3['freight'] = $arr3['freight'] - (float)number_format((float)$gongtong5['freight'] / 2, 3, '.', '');
                        $arr3['freightmj'] = $arr3['freightmj'] - (float)number_format((float)$gongtong5['freightmj'] / 2, 3, '.', '');
                        $arr3['material'] = $arr3['material'] - (float)number_format((float)$gongtong5['material'] / 2, 3, '.', '');
                        $info = $info . "
                            " . (float)number_format((float)$gongtong5['total_price'] / 2, 3, '.', '') . "(平分销售额)";
                    }
                }
                //五月特殊情况结束

                //九月特殊情况
                if (!empty($gongtong9)) {
                    if ($reportmonthtwo['timedate'] == '1661961600' || $reportmonthtwo['timedate'] == '1664553600') {
                        if ($admin['id'] == '33') {
                            $arr3['total_price'] = $arr3['total_price'] - (float)$gongtong9['total_price'];
                            $arr3['salesz'] = $arr3['salesz'] - (float)$gongtong9['total_price'];
                            $arr3['freight'] = $arr3['freight'] - (float)$gongtong9['freight'];
                            $arr3['freightmj'] = $arr3['freightmj'] - (float)$gongtong9['freightmj'];
                            $arr3['material'] = $arr3['material'] - $gongtong9['material'];
                            $info = $info . "
                            " . (float)$gongtong9['total_price'] . "(riceelcosmetics扣除销售额)";
                        }
                        if ($admin['id'] == '37') {
                            $arr3['total_price'] = (float)$gongtong9['total_price'];
                            $arr3['salesz'] = $arr3['total_price'];
                            $arr3['freight'] = (float)$gongtong9['freight'];
                            $arr3['freightmj'] = (float)$gongtong9['freightmj'];
                            $arr3['material'] = (float)$gongtong9['material'];
                            $info = $info . "
                            " . (float)$gongtong9['total_price'] . "(riceelcosmetics销售额)";
                        }
                    }
                }
                //九月特殊情况结束

                //                计算个人填写的广告消耗
                $arr3['salesz_discount'] = $arr3['salesz'] * 0.95;

                $arr3['info'] = $info;
                $arr3['createtime'] = time();
                $arr3['updatetime'] = time();
                $arr3['admin_id'] = $admin['id'];
                //                $arr3['timedate'] = $lastmonth_start;

                //计算个人填写的广告消耗
                // $timedate = 'createtime';
                // $wheretime2 = $timedate.'>='.$lastmonth_start.' and '.$timedate.'<'.$lastmonth_end;
                // $wheres = 'and type = 1 and admin_id = '.$admin['id'].' GROUP BY admin_id';
                //                 $sqlreport = "SELECT
                // SUM(amount) as advertisingz,admin_id
                // FROM fa_advertising_report
                // WHERE ".$wheretime2." ".$wheres;
                // $report = \think\Db::query($sqlreport);
                // if (!empty($report)) {
                //     if (!empty($report[0]['advertisingz']) && isset($report[0]['advertisingz'])) {
                //         $arr3['advertisingz'] = $report[0]['advertisingz'];
                //     }
                // } else {
                //     $arr3['advertisingz'] = 0;
                // }

                $arr3['zcost'] = $arr3['material'] + $arr3['freightmj'] + $reportmonthtwo['advertisingz'];
                $arr3['gross_profit'] = $arr3['salesz_discount'] - $arr3['zcost'];
                //单量跟单转成本
                if ($reportmonthtwo['advertisingz'] > 0 && $arr3['countnums'] > 0) {
                    $arr3['order_proportion'] = (float)number_format((float)$reportmonthtwo['advertisingz'] / $arr3['countnums'], 3, '.', '');
                } else {
                    $arr3['order_proportion'] = 0;
                }
            }
            table('fedition_reportmonthtwo')->where('id', $id)->update($arr3);
            $this->add_reportmonth_excel($id);
        } else {
            $this->success('运营已禁用');
        }

        $this->success('操作成功');
    }

    /**
     * 新增商品标题
     */
    public function producttitle()
    {

        $type = $this->request->request('type');
        $orderproduct = table('fedition_orderproduct')->select();
        if (!empty($orderproduct)) {
            foreach ($orderproduct as $item) {
                $shopify = $this->add_producttitle($item);
            }
            $this->success('操作成功', $shopify);
        } else {
            //            未找到相关订单
            $this->error('未找到相关订单');
        }
    }

    public function add_producttitle($ordershopify)
    {
        $accounturl = table('fedition_accounturl')->where('id', $ordershopify['accounturl'])->find();
        $url = $accounturl['shopifyname'] . "/admin/api/2021-07/products/" . $ordershopify['product_id'] . ".json";
        $data = $this->geturl($url, $accounturl['shopifyapikey'], $accounturl['shopifysecretapikey']);
        if ($data) {
            $data = json_decode($data, true);
            if (!empty($data['product'])) {
                $product = $data['product'];
                $arr['product_name'] = $product['title'];
                $shopify = table('fedition_orderproduct')->where('id', $ordershopify['id'])->update($arr);
            }
        }
        return true;
    }

    /**
     *5分钟更新一次订单
     */
    public function updateordertime($id = null)
    {
        if (!empty($id)) {
            $ordershopify = table('fedition_ordershopify')
                ->where('id', $id)
                ->select();
        } else {
            $ids = $this->request->request('ids');
            $where = array();
            if (!empty($ids)) {
                $where['accounturl'] = $ids;
            } else {
                //从56店铺开始更新
                $where['accounturl']  = array('egt', 56);
            }

            $thismonth = date('m');
            $thisyear = date('Y');
            if ($thismonth == 1) {
                $lastmonth = 11;
                $lastyear = $thisyear - 1;
            } elseif ($thismonth == 2) {
                $lastmonth = 12;
                $lastyear = $thisyear - 1;
            } else {
                $lastmonth = $thismonth - 2;
                $lastyear = $thisyear;
            }
            $lastStartDay = $lastyear . '-' . $lastmonth . '-1';
            $lastEndDay = $lastyear . '-' . $lastmonth . '-' . date('t', strtotime($lastStartDay)) . ' 23:59:59';
            $b_time = strtotime($lastStartDay); //上个月的月初时间戳
            $e_time = strtotime($lastEndDay); //上个月的月末时间戳

            // $where['created_at']  = array('egt',$b_time);
            // $where['created_at']  = array('elt',$e_time);
            $where['created_at'] = array(array('egt', $b_time), array('elt', $e_time));

            $ordershopify = table('fedition_ordershopify')
                ->order('updateordertime asc')
                ->where($where)
                ->limit('10')
                ->select();
        }
        if (!empty($ordershopify)) {
            $row = array();
            foreach ($ordershopify as $t) {
                $accountur = table('fedition_accounturl')
                    ->where('id', $t['accounturl'])
                    ->find();
                $url = $accountur['shopifyname'] . "/admin/api/2021-07/orders/" . $t['id'] . ".json";
                $data = $this->geturl($url, $accountur['shopifyapikey'], $accountur['shopifysecretapikey']);
                $data = json_decode($data, true);
                if (isset($data['order'])) {
                    //改变时间
                    if (!empty($data['order']['created_at'])) {
                        //直接截取获得时间戳
                        $ycreated_at2 = str_replace('T', ' ', $data['order']['created_at']);
                        $row['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '-'));
                    }
                    $row['ycreated_at'] = $data['order']['created_at'];
                    $row['created_at'] = strtotime($row['created_at']);
                    $product_tagsz = '';
                    //新增商品详情
                    if (isset($data['order']['line_items'])) {
                        $line_items = $data['order']['line_items'];
                        if (!empty($line_items)) {
                            foreach ($line_items as $line_item) {

                                $product_tags = array();
                                $url2 = $accountur['shopifyname'] . "/admin/api/2021-07/products/" . $line_item['product_id'] . ".json";
                                $data2 = $this->geturl($url2, $accountur['shopifyapikey'], $accountur['shopifysecretapikey']);
                                if ($data2) {
                                    $data2 = json_decode($data2, true);
                                    if (!empty($data2['product']['tags'])) {
                                        $product_tags = $data2['product']['tags'];
                                    }


                                    if (isset($data2['product']['images'][0]['src']) && !empty($data2['product']['images'][0]['src'])) {
                                        $product_images = $data2['product']['images'][0]['src'];
                                    }
                                }
                                //zhi有对应的店铺才能读取标签
                                if ($accountur['admin_type'] == 0) {
                                    $product_tags = array();
                                }
                                if (!empty($product_tags)) {
                                    if (!empty($product_tagsz)) {
                                        if ($product_tags !== $product_tagsz) {
                                            $product_tagsz = $product_tagsz . ',' . $product_tags;
                                        }
                                    } else {
                                        $product_tagsz = $product_tags;
                                    }
                                }

                                $arr['sku'] = $line_item['sku'];
                                $arr['title'] = $line_item['title'];
                                $arr['product_id'] = $line_item['product_id'];
                                $arr['price'] = $line_item['price'];
                                $arr['variant_id'] = $line_item['variant_id'];
                                $arr['variant_title'] = $line_item['variant_title'];
                                $arr['quantity'] = $line_item['quantity'];
                                //                                $arr['zmaterial'] = $arr['price'] * $arr['quantity'];
                                $arr['order_id'] = $t['id'];
                                $arr['createtime'] = time();
                                $arr['updatetime'] = time();
                                $arr['order_time'] = $t['created_at'];
                                $orderquantity = table('fedition_orderquantity')
                                    ->where('variant_id', $arr['variant_id'])
                                    ->where('order_id', $arr['order_id'])
                                    ->find();
                                if (empty($orderquantity)) {
                                    table('fedition_orderquantity')->insert($arr);
                                } else {
                                    if (!empty($product_tags) && isset($product_tags)) {
                                        $arr['user_id'] = $product_tags;
                                        table('fedition_orderquantity')
                                            ->where('variant_id', $arr['variant_id'])
                                            ->where('order_id', $arr['order_id'])
                                            ->update($arr);
                                    }
                                }
                                //商品记录
                                $orderproduct = table('fedition_orderproduct')->where('product_id', $arr['product_id'])->find();
                                if (empty($orderproduct)) {
                                    $product['createtime'] = time();
                                    $product['product_id'] = $arr['product_id'];
                                    $product['accounturl'] = $t['accounturl'];
                                    $product['product_name'] = $arr['title'];
                                    if (!empty($data2['product']['handle']) && isset($data2['product']['handle'])) {
                                        $product['handle_url'] = $accountur['shopifyname'] . '/products/' . $data2['product']['handle'];
                                    }
                                    if (!empty($product_images)) {
                                        $product['product_images'] = $product_images;
                                    }
                                    table('fedition_orderproduct')->insert($product);
                                } else {
                                    //修改商品归属人
                                    $product2 = array();
                                    if (!empty($product_tags) && isset($product_tags)) {
                                        $product2['user_id'] = $data2['product']['tags'];
                                    }
                                    if (!empty($data2['product']['handle']) && isset($data2['product']['handle'])) {

                                        $product2['handle_url'] = $accountur['shopifyname'] . '/products/' . $data2['product']['handle'];
                                    }
                                    if (!empty($product_images)) {
                                        $product2['product_images'] = $product_images;
                                    }
                                    if (!empty($product2)) {
                                        table('fedition_orderproduct')->where('product_id', $arr['product_id'])->update($product2);
                                    }
                                }
                                //如果sku库没有则添加
                                if (!empty($arr['variant_id'])) {
                                    $ordersku = table('fedition_ordersku')
                                        ->where('variants_id', $arr['variant_id'])
                                        ->find();
                                    if (empty($ordersku)) {
                                        $sku_arr['product_id'] = $arr['product_id'];
                                        $sku_arr['createtime'] = time();
                                        $sku_arr['updatetime'] = time();
                                        $sku_arr['variants_id'] = $arr['variant_id'];
                                        $sku_arr['sku'] = $arr['sku'];
                                        $sku_arr['material'] = 0;
                                        $sku_arr['accounturl'] = $t['accounturl'];
                                        table('fedition_ordersku')
                                            ->insert($sku_arr);
                                    }
                                }
                            }
                        }
                    }
                    //新增商品物流单
                    if (isset($data['order']['fulfillments'])) {
                        $fulfillments = $data['order']['fulfillments'];
                        if (!empty($fulfillments)) {
                            table('fedition_orderfulfillments')
                                ->where('order_id', $t['id'])
                                ->delete();
                            foreach ($fulfillments as $line_item) {
                                $arr2['tracking_ids'] = $line_item['id'];
                                $arr2['name'] = $line_item['name'];
                                $arr2['tracking_number'] = $line_item['tracking_number'];
                                $arr2['tracking_company'] = $line_item['tracking_company'];
                                $arr2['order_id'] = $line_item['order_id'];
                                $arr2['createtime'] = time();
                                $arr2['updatetime'] = time();
                                table('fedition_orderfulfillments')->insert($arr2);
                                $row['tracking_number'] = $line_item['tracking_number'];
                                $row['tracking_company'] = $line_item['tracking_company'];
                            }
                        }
                    }
                    //更新订单状态
                    if (!empty($data['order']['financial_status'])) {
                        //如果是退款的 部分退款的订单则不实时更新状态了
                        if ($data['order']['financial_status'] == 'refunded' || $data['order']['financial_status'] == 'partially_refunded') {
                            //也更新状态
                            $row['financial_status'] = $data['order']['financial_status'];
                        } else {
                            $row['financial_status'] = $data['order']['financial_status'];
                        }
                    } else {
                        $row['financial_status'] = 'unfulfilled';
                    }
                    $row['fulfillment_status'] = $data['order']['fulfillment_status'];
                    //                更新订单最新价格
                    $row['total_price'] = $data['order']['total_price'];
                    //计算小费
                    if (!empty($data['order']['total_tip_received'])) {
                        $row['total_tip_received'] = $data['order']['total_tip_received'];
                    }

                    if (isset($data['order']['customer']['total_spent']) && $data['order']['customer']['total_spent'] > 0 && $data['order']['financial_status'] == 'partially_refunded') {
                        $row['total_price'] = $data['order']['customer']['total_spent'];
                    }
                    if ($data['order']['financial_status'] == 'refunded') {
                        $row['total_price'] = 0;
                    }
                    //新增明细
                    if (isset($data['order']['current_subtotal_price'])) {
                        $row['current_subtotal_price'] = $data['order']['current_subtotal_price'];
                    } else {
                        $row['current_subtotal_price'] = 0;
                    }
                    // 可能是total_line_items_price
                    if (isset($data['order']['total_shipping_price_set']['shop_money']['amount'])) {
                        $row['total_shipping_price_set'] = $data['order']['total_shipping_price_set']['shop_money']['amount'];
                    } else {
                        $row['total_shipping_price_set'] = 0;
                    }

                    //联系人
                    if (isset($data['order']['customer']['email'])) {
                        $row['email'] = $data['order']['customer']['email'];
                    } else {
                        $row['email'] = '';
                    }
                    if (isset($data['order']['shipping_address']['name'])) {
                        $row['shipping_name'] = $data['order']['shipping_address']['name'];
                    } else {
                        $row['shipping_name'] = '';
                    }
                    if (isset($data['order']['shipping_address']['phone'])) {
                        $row['phone'] = str_replace(array("\r\n", "\r", " ", "\n"), "", $data['order']['shipping_address']['phone']);
                    } else {
                        $row['phone'] = '';
                    }
                    if (isset($data['order']['shipping_address']['province'])) {
                        $row['province'] = $data['order']['shipping_address']['province'];
                    } else {
                        $row['province'] = '';
                    }
                    if (isset($data['order']['shipping_address']['city'])) {
                        $row['city'] = $data['order']['shipping_address']['city'];
                    } else {
                        $row['city'] = '';
                    }
                    if (isset($data['order']['shipping_address']['zip'])) {
                        $row['zip'] = $data['order']['shipping_address']['zip'];
                    } else {
                        $row['zip'] = '';
                    }
                    if (isset($data['order']['shipping_address']['address1'])) {
                        $row['address1'] = $data['order']['shipping_address']['address1'];
                    } else {
                        $row['address1'] = '';
                    }
                    if (isset($data['order']['shipping_address']['country_code'])) {
                        $row['country_code'] = $data['order']['shipping_address']['country_code'];
                    } else {
                        $row['country_code'] = '';
                    }
                    if (isset($data['order']['order_status_url'])) {
                        $row['order_status_url'] = $data['order']['order_status_url'];
                    } else {
                        $row['order_status_url'] = '';
                    }
                    //note
                    $row['note'] = $data['order']['note'];
                    $row['tags'] = $data['order']['tags'];
                    $row['referring_site'] = $data['order']['referring_site'];
                    $row['landing_site'] = $data['order']['landing_site'];
                    //referring_site是空且landing_site带/的不要，instagram facebook不要
                    //该订单当前归属人
                    $wheregroup['createtime'] = array('elt', $row['created_at']);
                    $wheregroup['updatetime'] = array('egt', $row['created_at']);
                    $accounturlgroup = table('fedition_accounturlgroup')
                        ->where('accounturl', $accountur['id'])
                        ->where($wheregroup)
                        ->find();
                    // if (!empty($accounturlgroup)) {
                    //     $admin = table('admin')->where('id', $accounturlgroup['admin_id'])->find();
                    // }
                    //优先接口的标签
                    if (!empty($product_tagsz)) {
                        $row['user_id'] = $product_tagsz;
                        //再加店铺归属人
                        // if (!empty($admin) && $admin['id'] !== 1) {
                        //     $row['user_id'] = $row['user_id'].','.$admin['username'];
                        // }
                    } else {
                        //如果没有标签则用店铺归属人
                        // if (!empty($admin)) {
                        //     $row['user_id'] = $admin['username'];
                        // }else{
                        $row['user_id'] = 'Admin';
                        // }
                    }
                }
                $row['updateordertime'] = time();
                //同步物流消息
                //                if (empty($row['tracking_number'])) {
                $orderfulfillments = table('fedition_orderfulfillments')->where('order_id', $t['id'])->find();
                if (!empty($orderfulfillments)) {
                    $row['tracking_number'] = $orderfulfillments['tracking_number'];
                    $row['tracking_company'] = $orderfulfillments['tracking_company'];
                    $orderfulfillments['order_id'] = $t['id'];
                    $this->openpx($orderfulfillments);
                } else {
                    $row['tracking_number'] = '';
                    $row['tracking_company'] = '';
                }
                //                }
                table('fedition_ordershopify')
                    ->where('id', $t['id'])
                    ->update($row);
            }
            $this->success('操作成功');
        } else {
            $this->error('未找到相关订单');
        }
    }

    /**
     *5分钟更新一次订单
     */
    public function updateordertime_current($id = null)
    {
        if (!empty($id)) {
            $ordershopify = table('fedition_ordershopify')
                ->where('id', $id)
                ->select();
        } else {
            $b_time = strtotime('-4 days');
            $e_time = time();
            // $where['created_at']  = array('egt',$b_time);
            // $where['created_at']  = array('elt',$e_time);
            $where['created_at'] = array(array('egt', $b_time), array('elt', $e_time));
            $where['accounturl'] = array('in', '59,79,81');
            $ordershopify = table('fedition_ordershopify')
                ->order('updateordertime asc')
                ->where($where)
                ->limit('20')
                ->select();
        }
        if (!empty($ordershopify)) {
            $row = array();
            foreach ($ordershopify as $t) {
                $accountur = table('fedition_accounturl')
                    ->where('id', $t['accounturl'])
                    ->find();
                $url = $accountur['shopifyname'] . "/admin/api/2021-07/orders/" . $t['id'] . ".json";
                $data = $this->geturl($url, $accountur['shopifyapikey'], $accountur['shopifysecretapikey']);
                $data = json_decode($data, true);
                if (isset($data['order'])) {
                    //改变时间
                    if (!empty($data['order']['created_at'])) {
                        //直接截取获得时间戳
                        $ycreated_at2 = str_replace('T', ' ', $data['order']['created_at']);
                        $row['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '-'));
                    }
                    $row['ycreated_at'] = $data['order']['created_at'];
                    $row['created_at'] = strtotime($row['created_at']);
                    $product_tagsz = '';
                    //新增商品详情
                    if (isset($data['order']['line_items'])) {
                        $line_items = $data['order']['line_items'];
                        if (!empty($line_items)) {
                            foreach ($line_items as $line_item) {

                                $product_tags = array();
                                $url2 = $accountur['shopifyname'] . "/admin/api/2021-07/products/" . $line_item['product_id'] . ".json";
                                $data2 = $this->geturl($url2, $accountur['shopifyapikey'], $accountur['shopifysecretapikey']);
                                if ($data2) {
                                    $data2 = json_decode($data2, true);
                                    if (!empty($data2['product']['tags'])) {
                                        $product_tags = $data2['product']['tags'];
                                    }


                                    if (isset($data2['product']['images'][0]['src']) && !empty($data2['product']['images'][0]['src'])) {
                                        $product_images = $data2['product']['images'][0]['src'];
                                    }
                                }
                                //zhi有对应的店铺才能读取标签
                                if ($accountur['admin_type'] == 0) {
                                    $product_tags = array();
                                }
                                if (!empty($product_tags)) {
                                    if (!empty($product_tagsz)) {
                                        if ($product_tags !== $product_tagsz) {
                                            $product_tagsz = $product_tagsz . ',' . $product_tags;
                                        }
                                    } else {
                                        $product_tagsz = $product_tags;
                                    }
                                }

                                $arr['sku'] = $line_item['sku'];
                                $arr['title'] = $line_item['title'];
                                $arr['product_id'] = $line_item['product_id'];
                                $arr['price'] = $line_item['price'];
                                $arr['variant_id'] = $line_item['variant_id'];
                                $arr['variant_title'] = $line_item['variant_title'];
                                $arr['quantity'] = $line_item['quantity'];
                                //                                $arr['zmaterial'] = $arr['price'] * $arr['quantity'];
                                $arr['order_id'] = $t['id'];
                                $arr['createtime'] = time();
                                $arr['updatetime'] = time();
                                $arr['order_time'] = $t['created_at'];
                                $orderquantity = table('fedition_orderquantity')
                                    ->where('variant_id', $arr['variant_id'])
                                    ->where('order_id', $arr['order_id'])
                                    ->find();
                                if (empty($orderquantity)) {
                                    table('fedition_orderquantity')->insert($arr);
                                } else {
                                    if (!empty($product_tags) && isset($product_tags)) {
                                        $arr['user_id'] = $product_tags;
                                        table('fedition_orderquantity')
                                            ->where('variant_id', $arr['variant_id'])
                                            ->where('order_id', $arr['order_id'])
                                            ->update($arr);
                                    }
                                }
                                //商品记录
                                $orderproduct = table('fedition_orderproduct')->where('product_id', $arr['product_id'])->find();
                                if (empty($orderproduct)) {
                                    $product['createtime'] = time();
                                    $product['product_id'] = $arr['product_id'];
                                    $product['accounturl'] = $t['accounturl'];
                                    $product['product_name'] = $arr['title'];
                                    if (!empty($data2['product']['handle']) && isset($data2['product']['handle'])) {
                                        $product['handle_url'] = $accountur['shopifyname'] . '/products/' . $data2['product']['handle'];
                                    }
                                    if (!empty($product_images)) {
                                        $product['product_images'] = $product_images;
                                    }
                                    table('fedition_orderproduct')->insert($product);
                                } else {
                                    //修改商品归属人
                                    $product2 = array();
                                    if (!empty($product_tags) && isset($product_tags)) {
                                        $product2['user_id'] = $data2['product']['tags'];
                                    }
                                    if (!empty($data2['product']['handle']) && isset($data2['product']['handle'])) {

                                        $product2['handle_url'] = $accountur['shopifyname'] . '/products/' . $data2['product']['handle'];
                                    }
                                    if (!empty($product_images)) {
                                        $product2['product_images'] = $product_images;
                                    }
                                    if (!empty($product2)) {
                                        table('fedition_orderproduct')->where('product_id', $arr['product_id'])->update($product2);
                                    }
                                }
                                //如果sku库没有则添加
                                if (!empty($arr['variant_id'])) {
                                    $ordersku = table('fedition_ordersku')
                                        ->where('variants_id', $arr['variant_id'])
                                        ->find();
                                    if (empty($ordersku)) {
                                        $sku_arr['product_id'] = $arr['product_id'];
                                        $sku_arr['createtime'] = time();
                                        $sku_arr['updatetime'] = time();
                                        $sku_arr['variants_id'] = $arr['variant_id'];
                                        $sku_arr['sku'] = $arr['sku'];
                                        $sku_arr['material'] = 0;
                                        $sku_arr['accounturl'] = $t['accounturl'];
                                        table('fedition_ordersku')
                                            ->insert($sku_arr);
                                    }
                                }
                            }
                        }
                    }
                    //新增商品物流单
                    if (isset($data['order']['fulfillments'])) {
                        $fulfillments = $data['order']['fulfillments'];
                        if (!empty($fulfillments)) {
                            table('fedition_orderfulfillments')
                                ->where('order_id', $t['id'])
                                ->delete();
                            foreach ($fulfillments as $line_item) {
                                $arr2['tracking_ids'] = $line_item['id'];
                                $arr2['name'] = $line_item['name'];
                                $arr2['tracking_number'] = $line_item['tracking_number'];
                                $arr2['tracking_company'] = $line_item['tracking_company'];
                                $arr2['order_id'] = $line_item['order_id'];
                                $arr2['createtime'] = time();
                                $arr2['updatetime'] = time();
                                table('fedition_orderfulfillments')->insert($arr2);
                                $row['tracking_number'] = $line_item['tracking_number'];
                                $row['tracking_company'] = $line_item['tracking_company'];
                            }
                        }
                    }
                    //更新订单状态
                    if (!empty($data['order']['financial_status'])) {
                        //如果是退款的 部分退款的订单则不实时更新状态了
                        if ($data['order']['financial_status'] == 'refunded' || $data['order']['financial_status'] == 'partially_refunded') {
                            //也更新状态
                            $row['financial_status'] = $data['order']['financial_status'];
                        } else {
                            $row['financial_status'] = $data['order']['financial_status'];
                        }
                    } else {
                        $row['financial_status'] = 'unfulfilled';
                    }
                    $row['fulfillment_status'] = $data['order']['fulfillment_status'];
                    //                更新订单最新价格
                    $row['total_price'] = $data['order']['total_price'];
                    //计算小费
                    if (!empty($data['order']['total_tip_received'])) {
                        $row['total_tip_received'] = $data['order']['total_tip_received'];
                    }

                    if (isset($data['order']['customer']['total_spent']) && $data['order']['customer']['total_spent'] > 0 && $data['order']['financial_status'] == 'partially_refunded') {
                        $row['total_price'] = $data['order']['customer']['total_spent'];
                    }
                    if ($data['order']['financial_status'] == 'refunded') {
                        $row['total_price'] = 0;
                    }
                    //新增明细
                    if (isset($data['order']['current_subtotal_price'])) {
                        $row['current_subtotal_price'] = $data['order']['current_subtotal_price'];
                    } else {
                        $row['current_subtotal_price'] = 0;
                    }
                    // 可能是total_line_items_price
                    if (isset($data['order']['total_shipping_price_set']['shop_money']['amount'])) {
                        $row['total_shipping_price_set'] = $data['order']['total_shipping_price_set']['shop_money']['amount'];
                    } else {
                        $row['total_shipping_price_set'] = 0;
                    }

                    //联系人
                    if (isset($data['order']['customer']['email'])) {
                        $row['email'] = $data['order']['customer']['email'];
                    } else {
                        $row['email'] = '';
                    }
                    if (isset($data['order']['shipping_address']['name'])) {
                        $row['shipping_name'] = $data['order']['shipping_address']['name'];
                    } else {
                        $row['shipping_name'] = '';
                    }
                    if (isset($data['order']['shipping_address']['phone'])) {
                        $row['phone'] = str_replace(array("\r\n", "\r", " ", "\n"), "", $data['order']['shipping_address']['phone']);
                    } else {
                        $row['phone'] = '';
                    }
                    if (isset($data['order']['shipping_address']['province'])) {
                        $row['province'] = $data['order']['shipping_address']['province'];
                    } else {
                        $row['province'] = '';
                    }
                    if (isset($data['order']['shipping_address']['city'])) {
                        $row['city'] = $data['order']['shipping_address']['city'];
                    } else {
                        $row['city'] = '';
                    }
                    if (isset($data['order']['shipping_address']['zip'])) {
                        $row['zip'] = $data['order']['shipping_address']['zip'];
                    } else {
                        $row['zip'] = '';
                    }
                    if (isset($data['order']['shipping_address']['address1'])) {
                        $row['address1'] = $data['order']['shipping_address']['address1'];
                    } else {
                        $row['address1'] = '';
                    }
                    if (isset($data['order']['shipping_address']['country_code'])) {
                        $row['country_code'] = $data['order']['shipping_address']['country_code'];
                    } else {
                        $row['country_code'] = '';
                    }
                    if (isset($data['order']['order_status_url'])) {
                        $row['order_status_url'] = $data['order']['order_status_url'];
                    } else {
                        $row['order_status_url'] = '';
                    }
                    //note
                    $row['note'] = $data['order']['note'];
                    $row['tags'] = $data['order']['tags'];
                    $row['referring_site'] = $data['order']['referring_site'];
                    $row['landing_site'] = $data['order']['landing_site'];
                    //referring_site是空且landing_site带/的不要，instagram facebook不要
                    //该订单当前归属人
                    $wheregroup['createtime'] = array('elt', $row['created_at']);
                    $wheregroup['updatetime'] = array('egt', $row['created_at']);
                    $accounturlgroup = table('fedition_accounturlgroup')
                        ->where('accounturl', $accountur['id'])
                        ->where($wheregroup)
                        ->find();
                    // if (!empty($accounturlgroup)) {
                    //     $admin = table('admin')->where('id', $accounturlgroup['admin_id'])->find();
                    // }
                    //优先接口的标签
                    if (!empty($product_tagsz)) {
                        $row['user_id'] = $product_tagsz;
                        //再加店铺归属人
                        // if (!empty($admin) && $admin['id'] !== 1) {
                        //     $row['user_id'] = $row['user_id'].','.$admin['username'];
                        // }
                    } else {
                        //如果没有标签则用店铺归属人
                        // if (!empty($admin)) {
                        //     $row['user_id'] = $admin['username'];
                        // }else{
                        $row['user_id'] = 'Admin';
                        // }
                    }
                }
                $row['updateordertime'] = time();
                //同步物流消息
                //                if (empty($row['tracking_number'])) {
                $orderfulfillments = table('fedition_orderfulfillments')->where('order_id', $t['id'])->find();
                if (!empty($orderfulfillments)) {
                    $row['tracking_number'] = $orderfulfillments['tracking_number'];
                    $row['tracking_company'] = $orderfulfillments['tracking_company'];
                    $orderfulfillments['order_id'] = $t['id'];
                    $this->openpx($orderfulfillments);
                } else {
                    $row['tracking_number'] = '';
                    $row['tracking_company'] = '';
                }
                //                }
                table('fedition_ordershopify')
                    ->where('id', $t['id'])
                    ->update($row);
            }
            $this->success('操作成功');
        } else {
            $this->error('未找到相关订单');
        }
    }

    /**
     *5分钟更新一次订单----往前四个月都要持续更新
     */
    public function updateordertime_behind($id = null)
    {
        if (!empty($id)) {
            $ordershopify = table('fedition_ordershopify')
                ->where('id', $id)
                ->select();
        } else {
            $ids = $this->request->request('ids');
            $where = array();
            if (!empty($ids)) {
                $where['accounturl'] = $ids;
            } else {
                //从56店铺开始更新
                $where['accounturl']  = array('egt', 56);
            }

            $thismonth = date('m');
            $thisyear = date('Y');
            if ($thismonth == 1) {
                $lastmonth = 10;
                $lastyear = $thisyear - 1;
            } elseif ($thismonth == 2) {
                $lastmonth = 11;
                $lastyear = $thisyear - 1;
            } elseif ($thismonth == 3) {
                $lastmonth = 12;
                $lastyear = $thisyear - 1;
            } else {
                $lastmonth = $thismonth - 2;
                $lastyear = $thisyear;
            }
            $lastStartDay = $lastyear . '-' . $lastmonth . '-1';
            $b_time = strtotime($lastStartDay);
            $e_time = time();

            // $where['created_at']  = array('egt',$b_time);
            // $where['created_at']  = array('elt',$e_time);
            $where['created_at'] = array(array('egt', $b_time), array('elt', $e_time));

            $ordershopify = table('fedition_ordershopify')
                ->order('updateordertime asc')
                ->where($where)
                ->limit('10')
                ->select();
        }
        if (!empty($ordershopify)) {
            $row = array();
            foreach ($ordershopify as $t) {
                $accountur = table('fedition_accounturl')
                    ->where('id', $t['accounturl'])
                    ->find();
                $url = $accountur['shopifyname'] . "/admin/api/2021-07/orders/" . $t['id'] . ".json";
                $data = $this->geturl($url, $accountur['shopifyapikey'], $accountur['shopifysecretapikey']);
                $data = json_decode($data, true);
                if (isset($data['order'])) {
                    //改变时间
                    if (!empty($data['order']['created_at'])) {
                        //直接截取获得时间戳
                        $ycreated_at2 = str_replace('T', ' ', $data['order']['created_at']);
                        $row['created_at'] = substr($ycreated_at2, 0, strripos($ycreated_at2, '-'));
                    }
                    $row['ycreated_at'] = $data['order']['created_at'];
                    $row['created_at'] = strtotime($row['created_at']);
                    $product_tagsz = '';
                    //新增商品详情
                    if (isset($data['order']['line_items'])) {
                        $line_items = $data['order']['line_items'];
                        if (!empty($line_items)) {
                            foreach ($line_items as $line_item) {

                                $product_tags = array();
                                $url2 = $accountur['shopifyname'] . "/admin/api/2021-07/products/" . $line_item['product_id'] . ".json";
                                $data2 = $this->geturl($url2, $accountur['shopifyapikey'], $accountur['shopifysecretapikey']);
                                if ($data2) {
                                    $data2 = json_decode($data2, true);
                                    if (!empty($data2['product']['tags'])) {
                                        $product_tags = $data2['product']['tags'];
                                    }


                                    if (isset($data2['product']['images'][0]['src']) && !empty($data2['product']['images'][0]['src'])) {
                                        $product_images = $data2['product']['images'][0]['src'];
                                    }
                                }
                                //zhi有对应的店铺才能读取标签
                                if ($accountur['admin_type'] == 0) {
                                    $product_tags = array();
                                }
                                if (!empty($product_tags)) {
                                    if (!empty($product_tagsz)) {
                                        if ($product_tags !== $product_tagsz) {
                                            $product_tagsz = $product_tagsz . ',' . $product_tags;
                                        }
                                    } else {
                                        $product_tagsz = $product_tags;
                                    }
                                }

                                $arr['sku'] = $line_item['sku'];
                                $arr['title'] = $line_item['title'];
                                $arr['product_id'] = $line_item['product_id'];
                                $arr['price'] = $line_item['price'];
                                $arr['variant_id'] = $line_item['variant_id'];
                                $arr['variant_title'] = $line_item['variant_title'];
                                $arr['quantity'] = $line_item['quantity'];
                                //                                $arr['zmaterial'] = $arr['price'] * $arr['quantity'];
                                $arr['order_id'] = $t['id'];
                                $arr['createtime'] = time();
                                $arr['updatetime'] = time();
                                $arr['order_time'] = $t['created_at'];
                                $orderquantity = table('fedition_orderquantity')
                                    ->where('variant_id', $arr['variant_id'])
                                    ->where('order_id', $arr['order_id'])
                                    ->find();
                                if (empty($orderquantity)) {
                                    table('fedition_orderquantity')->insert($arr);
                                } else {
                                    if (!empty($product_tags) && isset($product_tags)) {
                                        $arr['user_id'] = $product_tags;
                                        table('fedition_orderquantity')
                                            ->where('variant_id', $arr['variant_id'])
                                            ->where('order_id', $arr['order_id'])
                                            ->update($arr);
                                    }
                                }
                                //商品记录
                                $orderproduct = table('fedition_orderproduct')->where('product_id', $arr['product_id'])->find();
                                if (empty($orderproduct)) {
                                    $product['createtime'] = time();
                                    $product['product_id'] = $arr['product_id'];
                                    $product['accounturl'] = $t['accounturl'];
                                    $product['product_name'] = $arr['title'];
                                    if (!empty($data2['product']['handle']) && isset($data2['product']['handle'])) {
                                        $product['handle_url'] = $accountur['shopifyname'] . '/products/' . $data2['product']['handle'];
                                    }
                                    if (!empty($product_images)) {
                                        $product['product_images'] = $product_images;
                                    }
                                    table('fedition_orderproduct')->insert($product);
                                } else {
                                    //修改商品归属人
                                    $product2 = array();
                                    if (!empty($product_tags) && isset($product_tags)) {
                                        $product2['user_id'] = $data2['product']['tags'];
                                    }
                                    if (!empty($data2['product']['handle']) && isset($data2['product']['handle'])) {

                                        $product2['handle_url'] = $accountur['shopifyname'] . '/products/' . $data2['product']['handle'];
                                    }
                                    if (!empty($product_images)) {
                                        $product2['product_images'] = $product_images;
                                    }
                                    if (!empty($product2)) {
                                        table('fedition_orderproduct')->where('product_id', $arr['product_id'])->update($product2);
                                    }
                                }
                                //如果sku库没有则添加
                                if (!empty($arr['variant_id'])) {
                                    $ordersku = table('fedition_ordersku')
                                        ->where('variants_id', $arr['variant_id'])
                                        ->find();
                                    if (empty($ordersku)) {
                                        $sku_arr['product_id'] = $arr['product_id'];
                                        $sku_arr['createtime'] = time();
                                        $sku_arr['updatetime'] = time();
                                        $sku_arr['variants_id'] = $arr['variant_id'];
                                        $sku_arr['sku'] = $arr['sku'];
                                        $sku_arr['material'] = 0;
                                        $sku_arr['accounturl'] = $t['accounturl'];
                                        table('fedition_ordersku')
                                            ->insert($sku_arr);
                                    }
                                }
                            }
                        }
                    }
                    //新增商品物流单
                    if (isset($data['order']['fulfillments'])) {
                        $fulfillments = $data['order']['fulfillments'];
                        if (!empty($fulfillments)) {
                            table('fedition_orderfulfillments')
                                ->where('order_id', $t['id'])
                                ->delete();
                            foreach ($fulfillments as $line_item) {
                                $arr2['tracking_ids'] = $line_item['id'];
                                $arr2['name'] = $line_item['name'];
                                $arr2['tracking_number'] = $line_item['tracking_number'];
                                $arr2['tracking_company'] = $line_item['tracking_company'];
                                $arr2['order_id'] = $line_item['order_id'];
                                $arr2['createtime'] = time();
                                $arr2['updatetime'] = time();
                                table('fedition_orderfulfillments')->insert($arr2);
                                $row['tracking_number'] = $line_item['tracking_number'];
                                $row['tracking_company'] = $line_item['tracking_company'];
                            }
                        }
                    }
                    //更新订单状态
                    if (!empty($data['order']['financial_status'])) {
                        //如果是退款的 部分退款的订单则不实时更新状态了
                        if ($data['order']['financial_status'] == 'refunded' || $data['order']['financial_status'] == 'partially_refunded') {
                            //也更新状态
                            $row['financial_status'] = $data['order']['financial_status'];
                        } else {
                            $row['financial_status'] = $data['order']['financial_status'];
                        }
                    } else {
                        $row['financial_status'] = 'unfulfilled';
                    }
                    $row['fulfillment_status'] = $data['order']['fulfillment_status'];
                    //                更新订单最新价格
                    $row['total_price'] = $data['order']['total_price'];
                    //计算小费
                    if (!empty($data['order']['total_tip_received'])) {
                        $row['total_tip_received'] = $data['order']['total_tip_received'];
                    }

                    if (isset($data['order']['customer']['total_spent']) && $data['order']['customer']['total_spent'] > 0 && $data['order']['financial_status'] == 'partially_refunded') {
                        $row['total_price'] = $data['order']['customer']['total_spent'];
                    }
                    if ($data['order']['financial_status'] == 'refunded') {
                        $row['total_price'] = 0;
                    }
                    //新增明细
                    if (isset($data['order']['current_subtotal_price'])) {
                        $row['current_subtotal_price'] = $data['order']['current_subtotal_price'];
                    } else {
                        $row['current_subtotal_price'] = 0;
                    }
                    // 可能是total_line_items_price
                    if (isset($data['order']['total_shipping_price_set']['shop_money']['amount'])) {
                        $row['total_shipping_price_set'] = $data['order']['total_shipping_price_set']['shop_money']['amount'];
                    } else {
                        $row['total_shipping_price_set'] = 0;
                    }

                    //联系人
                    if (isset($data['order']['customer']['email'])) {
                        $row['email'] = $data['order']['customer']['email'];
                    } else {
                        $row['email'] = '';
                    }
                    if (isset($data['order']['shipping_address']['name'])) {
                        $row['shipping_name'] = $data['order']['shipping_address']['name'];
                    } else {
                        $row['shipping_name'] = '';
                    }
                    if (isset($data['order']['shipping_address']['phone'])) {
                        $row['phone'] = str_replace(array("\r\n", "\r", " ", "\n"), "", $data['order']['shipping_address']['phone']);
                    } else {
                        $row['phone'] = '';
                    }
                    if (isset($data['order']['shipping_address']['province'])) {
                        $row['province'] = $data['order']['shipping_address']['province'];
                    } else {
                        $row['province'] = '';
                    }
                    if (isset($data['order']['shipping_address']['city'])) {
                        $row['city'] = $data['order']['shipping_address']['city'];
                    } else {
                        $row['city'] = '';
                    }
                    if (isset($data['order']['shipping_address']['zip'])) {
                        $row['zip'] = $data['order']['shipping_address']['zip'];
                    } else {
                        $row['zip'] = '';
                    }
                    if (isset($data['order']['shipping_address']['address1'])) {
                        $row['address1'] = $data['order']['shipping_address']['address1'];
                    } else {
                        $row['address1'] = '';
                    }
                    if (isset($data['order']['shipping_address']['country_code'])) {
                        $row['country_code'] = $data['order']['shipping_address']['country_code'];
                    } else {
                        $row['country_code'] = '';
                    }
                    if (isset($data['order']['order_status_url'])) {
                        $row['order_status_url'] = $data['order']['order_status_url'];
                    } else {
                        $row['order_status_url'] = '';
                    }
                    //note
                    $row['note'] = $data['order']['note'];
                    $row['tags'] = $data['order']['tags'];
                    $row['referring_site'] = $data['order']['referring_site'];
                    $row['landing_site'] = $data['order']['landing_site'];
                    //referring_site是空且landing_site带/的不要，instagram facebook不要
                    //该订单当前归属人
                    $wheregroup['createtime'] = array('elt', $row['created_at']);
                    $wheregroup['updatetime'] = array('egt', $row['created_at']);
                    $accounturlgroup = table('fedition_accounturlgroup')
                        ->where('accounturl', $accountur['id'])
                        ->where($wheregroup)
                        ->find();
                    // if (!empty($accounturlgroup)) {
                    //     $admin = table('admin')->where('id', $accounturlgroup['admin_id'])->find();
                    // }
                    //优先接口的标签
                    if (!empty($product_tagsz)) {
                        $row['user_id'] = $product_tagsz;
                        //再加店铺归属人
                        // if (!empty($admin) && $admin['id'] !== 1) {
                        //     $row['user_id'] = $row['user_id'].','.$admin['username'];
                        // }
                    } else {
                        //如果没有标签则用店铺归属人
                        // if (!empty($admin)) {
                        //     $row['user_id'] = $admin['username'];
                        // }else{
                        $row['user_id'] = 'Admin';
                        // }
                    }
                }
                $row['updateordertime'] = time();
                //同步物流消息
                //                if (empty($row['tracking_number'])) {
                $orderfulfillments = table('fedition_orderfulfillments')->where('order_id', $t['id'])->find();
                if (!empty($orderfulfillments)) {
                    $row['tracking_number'] = $orderfulfillments['tracking_number'];
                    $row['tracking_company'] = $orderfulfillments['tracking_company'];
                    $orderfulfillments['order_id'] = $t['id'];
                    $this->openpx($orderfulfillments);
                } else {
                    $row['tracking_number'] = '';
                    $row['tracking_company'] = '';
                }
                //                }
                table('fedition_ordershopify')
                    ->where('id', $t['id'])
                    ->update($row);
            }
            $this->success('操作成功');
        } else {
            $this->error('未找到相关订单');
        }
    }

    /**
     *
     */
    public function reportdaya($id = null, $type = 1)
    {
        Cache::rm('dayalist');
        header("Content-type:text/html;charset=utf-8");
        date_default_timezone_set('PRC');

        if (!empty($id)) {
            $reportdaya = table('fedition_reportdaya')
                ->where('id', $id)
                ->find();
            $timedates = $reportdaya['timedate'];
        } else {
            $timedates = $this->request->request('timedate');
            $numday = $this->request->request('numday');
            if (empty($timedates)) {
                $timedates = strtotime(date('Y-m-d'));
            }
        }
        if (empty($numday)) {
            $numday = 1;
        }
        if ($type == 2) {
            //上个月1号
            $timedates = strtotime(date('Y-m-01', strtotime('-1 month')));
            $numday = 31;
        }
        for ($i = 1; $i <= $numday; $i++) {
            if (!empty($timedates)) {
                $timedates2 = $timedates + 86400;
                $timedate = 'created_at';
                $times = $timedate . '>=' . $timedates . ' and ' . $timedate . '<=' . $timedates2;

                $admins = table('admin')
                    ->where('status', 'normal')
                    ->where('launch', '1')
                    ->select();
                if (!empty($admins)) {

                    $statistics2 = array();
                    foreach ($admins as $admin) {
                        $arr_daya['content'] = '';
                        $arr_daya['salesz'] = 0;
                        $arr_daya['tip_price'] = 0;
                        $arr_daya['single'] = 0;
                        //按时间归类的店铺
                        $accounturlgroup = table('fedition_accounturlgroup')
                            ->field("c.*,tc.admin_type,tc.name as accounturl_name")
                            ->alias('c')
                            ->join('fa_fedition_accounturl tc', 'c.accounturl = tc.id', 'left')
                            ->where(
                                [
                                    'c.admin_id' => $admin['id'],
                                    'tc.admin_type' => 2,
                                    'c.status' => 'normal'
                                ]
                            )
                            ->select();
                        if (!empty($accounturlgroup)) {
                            foreach ($accounturlgroup as $vgroup) {
                                if (!empty($vgroup)) {
                                    if ($vgroup['createtime'] <= $timedates && $vgroup['updatetime']  >= $timedates) {
                                        $sqla = "SELECT cast(sum(total_price) AS decimal(15,2)) as total_price
,cast(sum(total_tip_received) AS decimal(15,2)) as total_tip_received
,count(countnum) as countnums
,c.name as accounturl_name,c.id as accounturl_id
FROM fa_fedition_ordershopify as a
LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
WHERE " . $times . "
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
AND accounturl = " . $vgroup['accounturl'] . "
ORDER BY accounturl ASC";
                                        $statisticsa = \think\Db::query($sqla);
                                        if (!empty($statisticsa)) {
                                            if (!empty($statisticsa)) {
                                                foreach ($statisticsa as $sta2) {
                                                    if (!empty($sta2['accounturl_id'])) {
                                                        if (empty($sta2['total_tip_received'])) {
                                                            $sta2['total_tip_received'] = '0.00';
                                                        }
                                                        if (empty($sta2['total_price'])) {
                                                            $sta2['total_price'] = '0.00';
                                                        }
                                                        $arr_daya['content'] = $arr_daya['content'] . '' . $sta2['total_price'] . '(' . $sta2['accounturl_name'] . '),' . $sta2['total_tip_received'] . '(小费).';
                                                        $arr_daya['salesz'] += $sta2['total_price'];
                                                        $arr_daya['tip_price'] += $sta2['total_tip_received'];
                                                        $arr_daya['single'] += $sta2['countnums'];
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //按标签分类的店铺
                        switch ($admin['id']) {
                            case '26':
                                $tags = 'zsf';
                                break;
                            case '27':
                                $tags = 'HB';
                                break;
                            case '29':
                                $tags = 'ZY';
                                break;
                            case '30':
                                $tags = 'aohui';
                                break;
                            case '33':
                                $tags = 'CY';
                                break;
                            default:
                                $tags = 'nobady';
                        }
                        if ($tags == 'nobady') {
                            $statistics2 = array();
                        } else {
                            //共同拥有的订单
                            $wheretag0 = "(user_id like '%zsf%' and user_id like '%HB%')";
                            $sql = "SELECT cast(sum(total_price) AS decimal(15,2)) as total_price
,cast(sum(total_tip_received) AS decimal(15,2)) as total_tip_received
,count(countnum) as countnums
,c.name as accounturl_name,c.id as accounturl_id
FROM fa_fedition_ordershopify as a
LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
WHERE " . $wheretag0 . "
AND " . $times . "
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
AND c.admin_type = 1
AND accounturl = 57
GROUP BY accounturl
ORDER BY accounturl ASC";
                            $statistics = \think\Db::query($sql);
                            $together['total_price'] = 0;
                            $together['total_tip_received'] = 0;
                            $together['accounturl_id'] = 0;
                            if (!empty($statistics)) {
                                $together = $statistics[0];
                                if (empty($together['total_tip_received'])) {
                                    $together['total_tip_received'] = '0.00';
                                }
                                if (empty($together['total_price'])) {
                                    $together['total_price'] = '0.00';
                                }
                                $together['total_tip_received'] = $together['total_tip_received'] / 2;
                                $together['total_price'] = $together['total_price'] / 2;
                            }
                            //共同拥有的订单结束

                            //                            $wheretag = "(user_id like '%" . $admin['username'] . "%' OR user_id like '%" . $tags . "%')";
                            $wheretag = "user_id like '%" . $tags . "%'";
                            $sql2 = "SELECT cast(sum(total_price) AS decimal(15,2)) as total_price
,cast(sum(total_tip_received) AS decimal(15,2)) as total_tip_received
,count(countnum) as countnums
,c.name as accounturl_name,c.id as accounturl_id
FROM fa_fedition_ordershopify as a
LEFT JOIN fa_fedition_accounturl as c ON a.accounturl=c.id
WHERE " . $wheretag . "
AND " . $times . "
AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded')
AND c.admin_type = 1
GROUP BY accounturl
ORDER BY accounturl ASC";
                            $statistics2 = \think\Db::query($sql2);
                        }
                        if (!empty($statistics2)) {
                            foreach ($statistics2 as $sta) {
                                if (empty($sta['total_tip_received'])) {
                                    $sta['total_tip_received'] = '0.00';
                                }
                                if (empty($sta['total_price'])) {
                                    $sta['total_price'] = '0.00';
                                }
                                $arr_daya['content'] = $arr_daya['content'] . '' . $sta['total_price'] . '(' . $sta['accounturl_name'] . '),' . $sta['total_tip_received'] . '(小费).';
                                $arr_daya['salesz'] += $sta['total_price'];
                                $arr_daya['tip_price'] += $sta['total_tip_received'];
                                $arr_daya['single'] += $sta['countnums'];
                                if (!empty($together['accounturl_id']) && $sta['accounturl_id'] == $together['accounturl_id']) {
                                    $arr_daya['content'] = $arr_daya['content'] . '' . $together['total_price'] . '(' . $together['accounturl_name'] . '共有单),' . $together['total_tip_received'] . '(共有小费).';
                                    $arr_daya['salesz'] = $arr_daya['salesz'] - $together['total_price'];
                                    $arr_daya['tip_price'] = $sta['total_tip_received'] - $together['total_tip_received'];
                                }
                            }
                        }

                        $arr_daya['createtime'] = time();
                        $arr_daya['admin_id'] = $admin['id'];
                        $arr_daya['timedate'] = $timedates;
                        $arr_daya['pid'] = 0;
                        $fedition_reportdaya = table('fedition_reportdaya')
                            ->where('admin_id', $admin['id'])
                            ->where('timedate', $timedates)
                            ->find();
                        if (!empty($fedition_reportdaya)) {
                            table('fedition_reportdaya')
                                ->where('id', $fedition_reportdaya['id'])
                                ->update($arr_daya);
                        } else {
                            table('fedition_reportdaya')
                                ->insert($arr_daya);
                        }
                    }
                }
            }
            $timedates = $timedates + 86400;
        }
        $this->success('更新成功');
    }

    public function openpx($line_item)
    {
        //4PX
        if ($line_item['tracking_company'] == '4PX' && !empty($line_item['tracking_number'])) {
            $yapp_key = '15e7e7b7-f23a-4e00-a9f8-cba67091206a';
            $yformat = 'json';
            $ymethod = 'tr.order.tracking.get';
            list($msec, $sec) = explode(' ', microtime());
            $ytimestamp = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
            $yv = '1.0';
            $app_key = 'app_key' . $yapp_key;
            $format = 'format' . $yformat;
            $method = 'method' . $ymethod;
            $timestamp = 'timestamp' . $ytimestamp;
            $v = 'v' . $yv;
            $data['deliveryOrderNo'] = $line_item['tracking_number'];
            $body = json_encode($data);
            $appSecret = 'f767bd69-f011-43df-b168-f48ff80e8967';
            $sign = $app_key . '' . $format . '' . $method . '' . $timestamp . '' . $v . '' . $body . '' . $appSecret;
            $sign = md5($sign);
            //测试环境
            //            $url = 'http://open.sandbox.4px.com/router/api/service';
            //正式环境
            $url = 'http://open.4px.com/router/api/service';
            $url = $url . '?method=' . $ymethod . '&app_key=' . $yapp_key . '&v=' . $yv . '&timestamp=' . $ytimestamp . '&format=' . $yformat . '&sign=' . $sign;
            $data = $this->posturlopenpx($url, $data);
            $data = json_decode($data, true);
            if (!empty($data['data'])) {
                if (!empty($data['data']['trackingList'])) {
                    $trackingList = $data['data']['trackingList'];
                    table('fedition_orderopenpx')->where('tracking_number', $data['data']['deliveryOrderNo'])->delete();
                    if (!empty($trackingList)) {
                        $newitem = $trackingList[0];
                        foreach ($trackingList as $item) {
                            $arr = array();
                            $arr['order_id'] = $line_item['order_id'];
                            $arr['tracking_company'] = $line_item['tracking_company'];
                            $arr['tracking_number'] = $data['data']['deliveryOrderNo'];
                            $arr['country'] = $data['data']['destinationCountry'];
                            $arr['businessLinkCode'] = $item['businessLinkCode'];
                            $arr['occurDatetime'] = $item['occurDatetime'];
                            if (!empty($arr['occurDatetime'])) {
                                $arr['createtime'] = strtotime($arr['occurDatetime']);
                            }
                            $arr['occurLocation'] = $item['occurLocation'];
                            $arr['trackingContent'] = $item['trackingContent'];
                            table('fedition_orderopenpx')->where('tracking_number', $data['data']['deliveryOrderNo'])->insert($arr);
                        }
                        if (!empty($newitem['trackingContent'])) {
                            $tracking = array();
                            switch ($newitem['trackingContent']) {
                                case 'Parcel information received':
                                    $tracking['tracking_status'] = 'solicitation'; //揽件
                                    break;
                                case 'Delivered':
                                    $tracking['tracking_status'] = 'sign'; //签收
                                    break;
                                default:
                                    $tracking['tracking_status'] = 'way'; //在途
                            }
                            if (!empty($newitem['occurDatetime'])) {
                                $tracking['tracking_time'] = $newitem['occurDatetime'];
                            }
                            table('fedition_ordershopify')->where('id', $line_item['order_id'])->update($tracking);
                        }
                    }
                }
            }
        }
    }

    //检查订单跟采购成本是不是一样
    public function productmaterial_inspect()
    {
        $timedate = 'created_at';
        $lastmonth_start = '1630425600';
        $lastmonth_end = '1633017599';
        $reportmonth['accounturl'] = 12;
        $where2 = " accounturl = '" . $reportmonth['accounturl'] . "' ";

        $times = $timedate . '>=' . $lastmonth_start . ' and ' . $timedate . '<=' . $lastmonth_end;
        $sql = "SELECT *
FROM fa_fedition_ordershopify
WHERE " . $times . "
AND " . $where2 . "
AND (financial_status = 'paid' or financial_status = 'partially_refunded')
";
        $statistics = \think\Db::query($sql);
        $error = array();
        foreach ($statistics as $statistic) {
            $orderquantity = table('fedition_orderquantity')->where('order_id', $statistic['id'])->select();
            if (!empty($orderquantity)) {
                $material = 0;
                foreach ($orderquantity as $item) {
                    $ordersku = table('fedition_ordersku')->where('variants_id', $item['variant_id'])->find();
                    if (!empty($ordersku)) {
                        $material1 = $ordersku['material'] * $item['quantity'];
                        $material = $material + $material1;
                    } else {
                        //如果是小费则不计算
                        if ($item['title'] == 'Tip') {
                        } else {
                            $error['variant'][] = $item['id'];
                        }
                    }
                }
            } else {
                $error['order'][] = $statistic['id'];
            }
            if ((float)number_format((float)$material - $statistic['material'], 3, '.', '') == 0) {
            } else {
                $error['order2'][] = $statistic['id'];
            }
        }
        $this->success('操作成功', $error);
    }

    //变体价格没填 导致算商品详情表的话 采购成本不对
    public function fedition_productmaterial_v()
    {
        $timedate = 'created_at';
        $lastmonth_start = '1630425600';
        $lastmonth_end = '1633017599';
        $reportmonth['accounturl'] = 12;
        $where2 = " accounturl = '" . $reportmonth['accounturl'] . "' ";

        $times = $timedate . '>=' . $lastmonth_start . ' and ' . $timedate . '<=' . $lastmonth_end;
        $sql = "SELECT *
FROM fa_fedition_ordershopify
WHERE " . $times . "
AND " . $where2 . "
AND (financial_status = 'paid' or financial_status = 'partially_refunded')
";
        $statistics = \think\Db::query($sql);
        foreach ($statistics as $item) {
            $orders = table('fedition_orderquantity')->where('order_id', $item['id'])->select();
            foreach ($orders as $order) {
                if (!empty($order['variant_id'])) {
                    $variants[$order['variant_id']] = $order['variant_id'];
                }
            }
        }

        //统计变体
        $arr2 = array();
        foreach ($variants as $k => $v) {
            $where_created = array();
            $created_star = '1630425600';
            $created_end = '1633017599';
            $where_created['order_time'] = array(array('egt', $created_star), array('elt', $created_end));
            $where_created['variant_id'] = $k;

            $varquantity = table('fedition_orderquantity')->where($where_created)->select();
            $quantity = 0;
            $material = 0;
            foreach ($varquantity as $item) {
                $quantity = $quantity + $item['quantity'];
                if (!empty($item['variant_id'])) {
                    $ordersku = table('fedition_ordersku')->where('variants_id', $item['variant_id'])->find();
                    if (!empty($ordersku)) {
                        $material = $material + $ordersku['material'];
                    }
                }
                $arr2['title'] = $item['title'];
                $arr2['product_id'] = $item['product_id'];
                if (!empty($item['sku'])) {
                    $arr2['sku'] = $item['sku'];
                }
                if (!empty($item['variant_title'])) {
                    $arr2['variant_title'] = $item['variant_title'];
                }
                $arr2['variant_id'] = $item['variant_id'];
            }
            //计算总的productmaterial
            $arr2['createtime'] = time();
            $arr2['updatetime'] = time();

            $arr2['material'] = $material;
            $arr2['quantity'] = $quantity;
            $arr2['accounturl'] = $reportmonth['accounturl'];
            $arr2['timedate'] = $lastmonth_start;
            $accounturls = table('fedition_accounturl')->where('id', $arr2['accounturl'])->find();
            if (!empty($accounturls)) {
                $arr2['admin_id'] = $accounturls['admin_id'];
            } else {
                $arr2['admin_id'] = 0;
            }
            table('fedition_productmaterialc')->insert($arr2);
        }
        $this->success('操作成功');
    }

    public function fedition_productmaterial_p()
    {
        $timedate = 'created_at';
        $lastmonth_start = '1630425600';
        $lastmonth_end = '1633017599';
        $reportmonth['accounturl'] = 12;
        $where2 = " accounturl = '" . $reportmonth['accounturl'] . "' ";

        $times = $timedate . '>=' . $lastmonth_start . ' and ' . $timedate . '<=' . $lastmonth_end;
        $sql = "SELECT *
FROM fa_fedition_ordershopify
WHERE " . $times . "
AND " . $where2 . "
AND (financial_status = 'paid' or financial_status = 'partially_refunded')
";
        $statistics = \think\Db::query($sql);
        foreach ($statistics as $item) {
            $orders = table('fedition_orderquantity')->where('order_id', $item['id'])->select();
            foreach ($orders as $order) {
                if (!empty($order['product_id'])) {
                    $products[$order['product_id']] = $order['product_id'];
                }
            }
        }

        //统计商品
        $arr = array();
        foreach ($products as $k => $v) {
            $where_created = array();
            $created_star = '1630425600';
            $created_end = '1633017599';
            $where_created['order_time'] = array(array('egt', $created_star), array('elt', $created_end));
            $where_created['product_id'] = $k;

            $varquantity = table('fedition_orderquantity')->where($where_created)->select();
            $quantity = 0;
            $material = 0;
            foreach ($varquantity as $item) {
                $quantity = $quantity + $item['quantity'];
                if (!empty($item['variant_id'])) {
                    $ordersku = table('fedition_ordersku')->where('variants_id', $item['variant_id'])->find();
                    if (!empty($ordersku)) {
                        $material = $material + $ordersku['material'];
                    }
                }
                $arr['title'] = $item['title'];
                $arr['product_id'] = $item['product_id'];
            }
            //计算总的productmaterial
            $arr['createtime'] = time();
            $arr['updatetime'] = time();

            $arr['material'] = $material;
            $arr['quantity'] = $quantity;
            $arr['accounturl'] = $reportmonth['accounturl'];
            $arr['timedate'] = $lastmonth_start;
            $accounturls = table('fedition_accounturl')->where('id', $arr['accounturl'])->find();
            if (!empty($accounturls)) {
                $arr['admin_id'] = $accounturls['admin_id'];
            } else {
                $arr['admin_id'] = 0;
            }
            table('fedition_productmaterial')->insert($arr);
        }
        $this->success('操作成功');
    }

    public function update_order_time()
    {
        //统计商品
        $timedate = 'created_at';
        $lastmonth_start = '1630425600';
        $lastmonth_end = '1633017599';
        $reportmonth['accounturl'] = 12;
        $where2 = " accounturl = '" . $reportmonth['accounturl'] . "' ";

        $times = $timedate . '>=' . $lastmonth_start . ' and ' . $timedate . '<=' . $lastmonth_end;
        $sql = "SELECT *
FROM fa_fedition_ordershopify
WHERE " . $times . "
AND " . $where2 . "
AND (financial_status = 'paid' or financial_status = 'partially_refunded')
";
        $statistics = \think\Db::query($sql);

        foreach ($statistics as $k => $v) {
            $arr['order_time'] = '1627747201';
            table('fedition_orderquantity')->where('order_id', $v['id'])->update($arr);
        }

        $this->success('操作成功');
    }

    //找到没有商品详情的订单
    public function isproductmaterial()
    {
        $ordershopify = table('fedition_ordershopify')->select();
        foreach ($ordershopify as $item) {
            $orderquantity = table('fedition_orderquantity')->where('order_id', $item['id'])->find();
            if (empty($orderquantity)) {
                $ids[] = $item['id'];;
            }
        }
        $this->success('操作成功,已找到有疑问的订单', $ids);
    }

    /**
     * 检查店铺是否正常
     */
    public function isnormal()
    {
        $iscustom = table('fedition_accounturl')
            ->where('iscustom', 1)
            ->where('status', 'normal')
            ->select();
        if ($iscustom) {
            foreach ($iscustom as $k => $v) {
                $result[] = $this->store_isnormal($v);
            }
        }
        $this->success('操作成功', $result);
    }

    public function store_isnormal($iscustom)
    {
        $url = $iscustom['shopifyname'] . "/admin/api/2021-07/shop.json";
        $data = $this->geturl($url, $iscustom['shopifyapikey'], $iscustom['shopifysecretapikey']);
        $result = array();
        if ($data) {
            $data = json_decode($data, true);
            if (!empty($data['errors'])) {
                if ($data['errors'] == 'Unavailable Shop') {
                    //如果门店不可用，则报警
                    $result = $this->unavailable($iscustom);
                    return $result;
                }
            }
        }
    }

    public function unavailable($iscustom)
    {
        //        $params['mobile'] = '16607234106';
        //        $smsbao = new smsbao();
        //        $result = $smsbao->mobile($params['mobile'])->msg("您的店铺".$iscustom['name']."已下线，请尽快查看并处理")->send();
        //        if ($result) {
        // table('fedition_accounturl')
        //     ->where('id', $iscustom['id'])
        //     ->update(
        //         [
        //             'status' => 'unavailable',
        //         ]
        //     );
        //        }
        return $iscustom;
    }

    /**
     * orderproduct 新增商品对应的sku列表
     * read_products权限
     * read_inventory权限要开通
     */
    public function query_information()
    {
        $name = $this->request->request('name');
        if (!empty($name)) {
            $accounturl = table('fedition_accounturl')
                ->where('name', $name)
                ->where('iscustom', 1)
                ->find();
            if (!empty($accounturl)) {
                $data['token'] = $accounturl['shopifysecretapikey'];
                $data['url'] = $url = $accounturl['shopifyname'] . "/admin/api/2021-07/orders.json";
                //                $this->success('操作成功',$data);
                $msgs = 'token值：' . $data['token'] . '<br/>店铺地址：' . $data['url'];
                return $msgs;
            } else {
                $this->error('未找到该店铺');
            }
        } else {
            $this->error('参数错误，请加上店铺名称');
        }
    }

    /**
     * 估算运费
     */
    public function estimate_freight()
    {
        $sql = "SELECT id,tracking_number FROM fa_fedition_ordershopify
WHERE accounturl>='56'
AND created_at>='1656604800'
AND created_at<='1661961600'
AND istransfer='0'
ORDER BY transfertime DESC
";
        $test = \think\Db::query($sql);
        foreach ($test as $k => $v) {
            if (!empty($v['tracking_number'])) {
                $fedition_orderquantity = table('fedition_orderquantity')->where('order_id', $v['id'])->find();
                $orderquantity = table('fedition_orderquantity')->where('product_id', $fedition_orderquantity['product_id'])->select();
            }
            if (!empty($orderquantity)) {
                $arr = array();
                foreach ($orderquantity as $item) {
                    $ordershopify = table('fedition_ordershopify')
                        ->where('id', $item['order_id'])
                        ->where('istransfer', 1)
                        ->find();
                    if (!empty($ordershopify)) {
                        $arr['transfertime'] = time();
                        $arr['freightmj'] = $ordershopify['freightmj'];
                        $arr['freight'] = $ordershopify['freight'];
                        $arr['istransfer'] = 11;
                        table('fedition_ordershopify')->where('id', $v['id'])->update($arr);
                        break;
                    }
                }
            }
        }
    }

    /**
     * 检查是否有报告
     */
    public function isreports()
    {
        $isreports = table('fedition_accounturl')
            ->where('id', 57)
            ->where('status', 'normal')
            ->select();
        if ($isreports) {
            foreach ($isreports as $k => $v) {
                $result[] = $this->store_isreports($v);
            }
        }
        $this->success('操作成功', $result);
    }

    public function store_isreports($iscustom)
    {
        $url = $iscustom['shopifyname'] . "/admin/api/2021-07/reports.json";
        dump($url);
        $data = $this->geturl($url, $iscustom['shopifyapikey'], $iscustom['shopifysecretapikey']);
        $result = array();
        dump($data);
        die;
        if ($data) {
            $data = json_decode($data, true);
            if (!empty($data['errors'])) {
                return $data['errors'];
            }
        }
    }

    /**
     * 后台自动获取数据
     * $type 1 拉取所有
     * $type 2 实时拉取当下
     * $type 3 拉取之前的
     */

    public function accounturl_product()
    {
        $type = $this->request->request('type');

        $where = array();
        $result = array();
        $accounturl = $this->request->request('accounturl');
        if (!empty($accounturl)) {
            $where['id'] = $accounturl;
        } else {
            //从56店铺开始更新
            $where['id']  = array('egt', 56);
        }
        if (!empty($type)) {
            $iscustom = table('fedition_accounturl')
                ->where('iscustom', 1)
                ->where('status', 'normal')
                ->where($where)
                ->order('updatetime_product asc')
                ->find();
            if ($iscustom) {
                $result[] = $this->products($iscustom, $type);
            }
        }
        $this->success('操作成功', $result);
    }

    /**
     * 方法详情
     * @param array params
     */
    public function update_product($params)
    {
        if (!empty($params)) {
            $where['id'] = $params;
            $iscustom = table('fedition_accounturl')
                ->where('iscustom', 1)
                ->where('status', 'normal')
                ->where($where)
                ->order('updatetime_product asc')
                ->find();
            if ($iscustom) {
                $result[] = $this->products($iscustom, 2);
            }
        }
        return $result;
    }

    /**
     * orders
     */
    public function products($iscustom, $type)
    {
        $url = $iscustom['shopifyname'] . "/admin/api/2021-07/products.json";
        $limit = 50;
        if ($type == 3) {
            $limit = 250;
            $before_ordershopify = table('products_shopify')
                ->where('accounturl', $iscustom['id'])
                ->order('ycreated_at asc')
                ->find();
            if ($before_ordershopify) {
                $created_at_max = $before_ordershopify['ycreated_at'];
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $created_at_max1 = date('Y-m-d', strtotime("now"));
                $created_at_max2 = date('H:i:s', strtotime("now"));
                $created_at_max = $created_at_max1 . 'T' . $created_at_max2 . '-04:00';
            }
            //拉取之前的订单
            $url = $url . '?created_at_max=' . $created_at_max;
        }
        if ($type == 2) {
            $limit = 20;
            $last_ordershopify = table('products_shopify')
                ->where('accounturl', $iscustom['id'])
                ->order('ycreated_at desc')
                ->find();
            if ($last_ordershopify) {
                $updated_at_min = $last_ordershopify['yupdated_at'];
                $updated_at_mins = explode('T', $updated_at_min);
                $updated_at_mins[0] = date('Y-m-d', strtotime("$updated_at_mins[0]-1day"));
                $updated_at_min = $updated_at_mins[0] . 'T' . $updated_at_mins[1];
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $updated_at_min = '2021-07-01T00:00:00-04:00';
            }
            $url = $url . '?updated_at_min=' . $updated_at_min;
        }
        //只查vendor
        if ($type == 4) {
            $limit = 250;
            $url = $url . '?vendor=Tracking';
        }
        if ($type == 1) {
            $url = $url . '?limit=' . $limit;
        } else {
            $url = $url . '&limit=' . $limit;
        }
        if ($type == 5) {
            $url = $iscustom['shopifyname'] . "/admin/api/2021-07/collections/275192283179/products.json";
        }
        $data = $this->geturl($url, $iscustom['shopifyapikey'], $iscustom['shopifysecretapikey']);
        $result = array();
        if ($data) {
            $data = json_decode($data, true);

            if (!empty($data['errors'])) {
                $updatetime_producte['updatetime_product'] = time();
                // $updatetime_producte['status'] = 'unavailable';
                // table('fedition_accounturl')
                //     ->where('id', $iscustom['id'])
                //     ->update($updatetime_producte);
                return $iscustom['shopifyname'] . '-' . $data['errors'];
            }
            $products = $data['products'];
            if (is_array($products) && !empty($products)) {
                date_default_timezone_set('Asia/Shanghai');
                foreach ($products as $k => $v) {
                    //添加到sku商品表中，获取sku
                    // $orderproducts = table('fedition_orderproduct')->where('product_id',$v['id'])->find();
                    // if(empty($orderproducts)){
                    //     $orderproducta['accounturl'] = $iscustom['id'];
                    //     $orderproducta['createtime'] = time();
                    //     $orderproducta['product_id'] = $v['id'];
                    //     $orderproducta['product_name'] = $v['title'];
                    //     table('fedition_orderproduct')->insert($orderproducta);
                    // }
                    //添加到sku商品表，获取sku结束
                    $row = $this->productmodel->get($v['id']);
                    $arr['id'] = $v['id'];
                    $arr['title'] = $v['title'];
                    $arr['body_html'] = $v['body_html'];
                    $arr['vendor'] = $v['vendor'];
                    $arr['product_type'] = $v['product_type'];
                    //美国时间转北京时间
                    $arr['ycreated_at'] = $v['created_at'];
                    $arr['yupdated_at'] = $v['updated_at'];
                    //显示美国时间,中国比美国快十二个小时

                    $arr['tags'] = $v['tags'];
                    $arr['status'] = $v['status'];
                    if ($type == 5) {
                        $arr['collections'] = 275192283179;
                    }

                    if (!empty($v['images'])) {
                        $arr['images'] = $v['images'][0]['src'];
                    }

                    // 备份数据
                    if (!empty($v['images'])) {
                        $arr['images2'] = json_encode($v['images'], true);
                    }
                    if (!empty($v['options'])) {
                        $arr['options'] = json_encode($v['options'], true);
                    }

                    if (!empty($v['variants'])) {
                        table('products_shopify_variants')->where('product_id', $v['id'])->delete();
                        foreach ($v['variants'] as $ka => $va) {
                            $vas['sku'] = $va['sku'];
                            $vas['price'] = $va['price'];
                            $vas['accounturl'] = $iscustom['id'];
                            $vas['product_id'] = $va['product_id'];
                            $vas['variants_id'] = $va['id'];
                            $vas['title'] = $va['title'];
                            $vas['option1'] = $va['option1'];
                            $vas['option2'] = $va['option2'];
                            $vas['option3'] = $va['option3'];
                            table('products_shopify_variants')->insert($vas);
                        }
                    }

                    $arr['accounturl'] = $iscustom['id'];
                    if ($row) {
                        // if ($row['yupdated_at'] !== $arr['yupdated_at']) {
                        $result = $row->save($arr);
                        // } else {
                        // $result = '重复';
                        // }
                    } else {
                        $result = $this->productmodel->insert($arr);
                    }
                }
            }
        }
        $updatetime_product['updatetime_product'] = time();
        table('fedition_accounturl')
            ->where('id', $iscustom['id'])
            ->update($updatetime_product);
        return 1;
    }

    /**
     * 方法详情
     * @param array params
     */
    public function sku_goods($id, $params)
    {
        $return = array();
        if (!empty($id)) {
            $ids = explode(',', $id);
            foreach ($ids as $k => $v) {
                $this->accounturl_product2($v);
            }
        }

        return $return;
    }
    /**
     * 方法详情
     * @param array params
     */
    public function needless($id, $params)
    {
        $return = array();
        if (!empty($id)) {
            $ids = explode(',', $id);
            foreach ($ids as $k => $v) {
                $this->needless2($v);
            }
        }
        return $return;
    }

    public function needless2($v)
    {
        $update['updatestatus'] = 'needless';
        table('products_shopify')->where('id', $v)->update($update);
        return 1;
    }

    public function accounturl_product2($id = null)
    {
        // $ids = $this->request->request('ids');
        // if(!empty($ids)){
        //     $id = $ids;
        // }
        if (!empty($id)) {
            $products_shopify = table('products_shopify')
                ->where('id', $id)
                ->select();
        } else {
            $products_shopify = table('products_shopify')
                ->order('updateordertime asc')
                ->where('updatestatus', 'hidden')
                ->limit('2')
                ->select();
        }

        if (!empty($products_shopify)) {
            $data1['updatestatus'] = 'unavailable';
            foreach ($products_shopify as $k => $v) {

                //先更新一遍再生成SKU
                $iscustom = table('fedition_accounturl')
                    ->where('id', $v['accounturl'])
                    ->find();
                $url = $iscustom['shopifyname'] . "/admin/api/2021-07/products/" . $v['id'] . ".json";
                $ldata = $this->geturl($url, $iscustom['shopifyapikey'], $iscustom['shopifysecretapikey']);

                if ($ldata) {
                    $ldata2 = json_decode($ldata, true);
                    if (!empty($ldata2['product'])) {
                        $lproduct = $ldata2['product'];
                        $larr['title'] = $lproduct['title'];
                        $larr['product_type'] = $lproduct['product_type'];
                        $larr['ycreated_at'] = $lproduct['created_at'];
                        $larr['yupdated_at'] = $lproduct['updated_at'];
                        //显示美国时间,中国比美国快十二个小时

                        if (!empty($v['images'])) {
                            $larr['images'] = $lproduct['images'][0]['src'];
                        }

                        // 备份数据
                        if (!empty($v['images'])) {
                            $larr['images2'] = json_encode($lproduct['images'], true);
                        }
                        if (!empty($v['options'])) {
                            $larr['options'] = json_encode($lproduct['options'], true);
                        }

                        if (!empty($lproduct['variants'])) {
                            table('products_shopify_variants')->where('product_id', $v['id'])->delete();
                            foreach ($lproduct['variants'] as $ka => $va) {
                                $vas['sku'] = $va['sku'];
                                $vas['price'] = $va['price'];
                                $vas['accounturl'] = $iscustom['id'];
                                $vas['product_id'] = $va['product_id'];
                                $vas['variants_id'] = $va['id'];
                                $vas['title'] = $va['title'];
                                $vas['option1'] = $va['option1'];
                                $vas['option2'] = $va['option2'];
                                $vas['option3'] = $va['option3'];
                                table('products_shopify_variants')->insert($vas);
                            }
                        }
                        table('products_shopify')
                            ->where('id', $v['id'])
                            ->update($larr);
                    }
                }

                $shopify_variants = table('products_shopify_variants')
                    ->where('product_id', $v['id'])
                    ->order('id asc')
                    ->select();

                if (!empty($shopify_variants) && !empty($v['product_type'])) {
                    $num = table('products_shopify')
                        ->where('product_type', $v['product_type'])
                        ->where('updatestatus', 'normal')
                        ->count();
                    if ($num == 0) {
                        $num = '0001';
                    } else {
                        $num = sprintf("%03d", $num);
                    }
                    $newvariants = array();
                    foreach ($shopify_variants as $key => $val) {
                        // if(!empty($val['sku'])){
                        //     $sku = $val['sku'];
                        // }else{
                        $sku = $v['product_type'] . '-' . $num;
                        if (!empty($val['option1'])) {
                            $sku = $sku . '-' . $val['option1'];
                        }
                        if (!empty($val['option2'])) {
                            $sku = $sku . '-' . $val['option2'];
                        }
                        if (!empty($val['option3'])) {
                            $sku = $sku . '-' . $val['option3'];
                        }
                        // }

                        $variants['sku'] = $sku;
                        $shopify_variants = table('products_shopify_variants')->where('id', $val['id'])->update($variants);
                        $newvariants[$key]['id'] = $val['variants_id'];
                        $newvariants[$key]['sku'] = $sku;
                    }
                    if (!empty($newvariants)) {
                        $url = $iscustom['shopifyname'] . "/admin/api/2021-07/products/" . $v['id'] . ".json";
                        $newdata = array();
                        $newdata['product']['id'] = $v['id'];
                        $newdata['product']['title'] = $v['title'];
                        $newdata['product']['variants'] = $newvariants;

                        $newreturn = $this->puturl($url, $newdata, $iscustom);
                        if (!empty($newreturn)) {
                            $datareturn = json_decode($newreturn, true);
                            if (isset($datareturn['product']['id']) && !empty($datareturn['product']['id'])) {
                                $data1['updatestatus'] = 'normal';
                            }
                        }
                    }
                }
                $products_shopify = table('products_shopify')
                    ->where('id', $v['id'])
                    ->update($data1);
            }
        }
        return 1;
    }

    //商品添加 转移
    public function products_add($id, $params)
    {
        $ids = explode(',', $id);
        $infos = '';
        $infos2 = '';
        $nums = 0;
        $errors = 0;
        $cover = 0;
        foreach ($ids as $k => $v) {
            $return = $this->accounturl_product3($v, $params);
            if ($return == 3) {
                $errors += 1;
                $infos2 = $infos2 . '（' . $v . '）,';
            } elseif ($return == 2) {
                $cover += 1;
            } else {
                $nums += 1;
                $infos = $infos . '（' . $return . '）,';
            }
        }
        // $infos = '成功复制商品'.$nums.'条，失败'.$errors.'条'.$infos2.'，店铺已存在该商品'.$cover.'条'.$infos;
        $infos = '成功复制商品' . $nums . '条' . $infos . '，失败' . $errors . '条' . $infos2;
        return $infos;
    }

    //
    /**
     * 方法详情
     * @param array params
     */
    // http://121.5.76.151:100/Api/Myshopify/api_products_transfer?oldid=59&newid=87
    public function api_products_transfer()
    {
        $accounturly = $this->request->request('oldid');
        $accounturl = $this->request->request('newid');
        $products = table('products_shopify')
            ->where('accounturl', $accounturly)
            ->where('collections', 275192283179)
            ->where('transfer_status', 0)
            ->order('transfer_time asc')
            ->find();
        $returns = 402;
        if (!empty($products)) {
            $return = $this->accounturl_product3($products['id'], $accounturl);
            $arr['transfer_time'] = time();
            if ($return == 3) {
                $arr['transfer_status'] = 2;
            } else {
                $arr['transfer_status'] = 1;
            }
            $returns = table('products_shopify')
                ->where('id', $products['id'])
                ->update($arr);
        }
        $this->success('操作完成', $returns);
    }


    public function accounturl_product3($id, $params)
    {
        $products_shopify = table('products_shopify')
            ->where('id', $id)
            ->find();
        $msgs = 3;

        if (!empty($products_shopify)) {
            // if($products_shopify['accounturl'] == $params){
            //     $msgs = 2;
            // }else{
            //先更新一遍再生成SKU
            $iscustom = table('fedition_accounturl')
                ->where('id', $products_shopify['accounturl'])
                ->find();
            $url = $iscustom['shopifyname'] . "/admin/api/2021-07/products/" . $products_shopify['id'] . ".json";
            $ldata = $this->geturl($url, $iscustom['shopifyapikey'], $iscustom['shopifysecretapikey']);
            $larr = array();
            if ($ldata) {
                $ldata2 = json_decode($ldata, true);
                if (!empty($ldata2['product'])) {
                    $lproduct = $ldata2['product'];
                    $larr['title'] = $lproduct['title'];
                    $larr['body_html'] = $lproduct['body_html'];
                    $larr['vendor'] = $lproduct['vendor'];
                    $larr['product_type'] = $lproduct['product_type'];
                    $larr['tags'] = $lproduct['tags'];
                    $larr['status'] = $lproduct['status'];
                    $larr['variants'] = array();
                    $larr['options'] = array();
                    $larr['images'] = array();
                    if (!empty($lproduct['variants'])) {
                        foreach ($lproduct['variants'] as $kvariants => $vvariants) {
                            $avariants = array();
                            $avariants['option1'] = $vvariants['option1'];
                            $avariants['price'] = $vvariants['price'];
                            $avariants['sku'] = $vvariants['sku'];
                            $avariants['option1'] = $vvariants['option1'];
                            $avariants['option2'] = $vvariants['option2'];
                            $avariants['option3'] = $vvariants['option3'];
                            $larr['variants'][] = $avariants;
                        }
                    }
                    if (!empty($lproduct['options'])) {
                        foreach ($lproduct['options'] as $koptions => $voptions) {
                            $aoptions = array();
                            $aoptions['name'] = $voptions['name'];
                            if (!empty($voptions['values'])) {
                                $aoptions['values'] = implode(',', $voptions['values']);
                            }
                            $larr['options'][] = $aoptions;
                        }
                    }
                    if (!empty($lproduct['images'])) {
                        foreach ($lproduct['images'] as $kimages => $vimages) {
                            $aimages = array();
                            $aimages['src'] = $vimages['src'];
                            $larr['images'][] = $aimages;
                        }
                    }
                }
            }
            if (!empty($larr)) {
                $newdata['product'] = $larr;
                $iscustom2 = table('fedition_accounturl')
                    ->where('id', $params)
                    ->find();
                $url2 = $iscustom2['shopifyname'] . "/admin/api/2021-07/products.json";
                $newreturn = $this->posturl($url2, $newdata, $iscustom2);

                if (!empty($newreturn)) {
                    $datareturn = json_decode($newreturn, true);
                    if (isset($datareturn['product']['id']) && !empty($datareturn['product']['id'])) {
                        $msgs = $datareturn['product']['id'];
                    }
                }
            }
            // }
            return $msgs;
        } else {
            return $msgs;
        }
    }

    /**
     * 干预采购成本跟历史保持一致
     * @param array params
     */
    public function feditionorderquantity()
    {
        $where_shopify['b.financial_status'] = array('in', 'paid,refunded,partially_refunded');
        // $where_shopify['b.fulfillment_status'] = 'fulfilled';
        $where_shopify['b.ismaterial'] = array('in', '0,3');
        $where_shopify['b.created_at'] =  ['between', ['1648742400', time()]];
        $where2['accounturl']  = array('egt', 56);

        $list = table('fedition_orderquantity')
            ->field("a.*,b.accounturl,b.name as order_name")
            ->alias('a')
            ->join('fa_fedition_ordershopify b', 'b.id = a.order_id', 'left')
            ->join('fa_fedition_accounturl c', 'b.accounturl = c.id', 'left')
            ->where($where2)
            ->where($where_shopify)
            ->group('a.product_id')
            ->order('b.accounturl', 'desc')
            ->order('a.product_id', 'desc')
            ->select();

        $ordersku = array();
        $return = array();
        foreach ($list as $k => $v) {
            if (!empty($v['variant_id'])) {
                $ordersku = table('fedition_ordersku')->where('variants_id', $v['variant_id'])->find();

                if (!empty($ordersku)) {
                    $sku = table('fedition_ordersku')
                        ->where('sku', $ordersku['sku'])
                        ->where('material', '>', '0.01')
                        ->order('material asc')
                        ->find();
                    if (!empty($sku)) {
                        if ($sku['variants_id'] == $ordersku['variants_id']) {
                            $return[] = 2;
                        } else {
                            $update['material'] = $sku['material'];
                            $return[] = table('fedition_ordersku')
                                ->where('sku', $ordersku['sku'])
                                ->update($update);
                        }
                    } else {
                        $return[] = 0;
                    }
                } else {
                    $return[] = '-1';
                }
            } else {
                $return[] = '-2';
            }
        }
        dump($return);
        die;
    }

    /**
     * 方法详情
     * @param array params
     */
    public function feditionorderquantity2()
    {
        $sql = "SELECT * FROM fa_fedition_ordersku
        where sku like '%bra%'
        and material>0.01
        GROUP BY sku
        order by material asc";
        $info = \think\Db::query($sql);
        $return = array();
        foreach ($info as $k => $v) {
            $update['material'] = $v['material'];
            $return[] = table('fedition_ordersku')
                ->where('sku', $v['sku'])
                ->update($update);
        }
        dump($return);
        die;
    }

    /**
     * 方法详情
     * @param array params
     */
    public function fa_aaaaaaaa()
    {
        $fa_aaaaaaaa = table('aaaaaaaa')
            ->where('f', '<', '6')
            ->select();
        foreach ($fa_aaaaaaaa as $k => $v) {
            $ordershopifycount = table('fedition_ordershopify')
                ->where('email', $v['b'])
                // ->where('city',$v['c'])
                ->where('total_price', $v['d'])
                ->count();
            $update = array();
            $update['f'] = 0;
            $update['g'] = 0;
            $update['i'] = 0;
            if ($ordershopifycount == 1) {
                $ordershopify = table('fedition_ordershopify')
                    ->where('email', $v['b'])
                    // ->where('city',$v['c'])
                    ->where('total_price', $v['d'])
                    ->find();
                if (!empty($ordershopify)) {
                    $update['f'] = $ordershopify['id'];
                    $update['g'] = $ordershopify['accounturl'];
                    $update['i'] = $ordershopify['tracking_number'];
                    table('aaaaaaaa')->where('id', $v['id'])->update($update);
                } else {
                    $update['f'] = '-1';
                    table('aaaaaaaa')->where('id', $v['id'])->update($update);
                }
            } else {
                $update['f'] = $ordershopifycount;
                table('aaaaaaaa')->where('id', $v['id'])->update($update);
            }
        }
    }

    /**
     * 方法详情
     * @param array params
     */
    public function fa_a2()
    {
        $fa_aaaaaaaa = table('aaaaaaaa_copy')
            ->select();
        foreach ($fa_aaaaaaaa as $k => $v) {
            $ordershopifycount = table('fedition_ordershopify')
                ->where('tracking_number', $v['a'])
                ->count();
            $update = array();
            $update['f'] = 0;
            $update['g'] = 0;
            if ($ordershopifycount == 1) {
                $ordershopify = table('fedition_ordershopify')
                    ->where('tracking_number', $v['a'])
                    ->find();
                if (!empty($ordershopify)) {
                    $update['f'] = $ordershopify['id'];
                    $update['g'] = $ordershopify['accounturl'];
                    table('aaaaaaaa_copy')->where('id', $v['id'])->update($update);
                } else {
                    $update['f'] = '-1';
                    table('aaaaaaaa_copy')->where('id', $v['id'])->update($update);
                }
            } else {
                $update['f'] = $ordershopifycount;
                table('aaaaaaaa_copy')->where('id', $v['id'])->update($update);
            }
        }
    }

    /**
     * 方法详情
     * @param array params
     */
    public function redis_test()
    {
        $arr['key'] = 1;
        // 队列处理
        $job = "addons\aqueue\library\jobs\RedisJobnew";
        $queue = "newpixelnew";
        $test = Queue::push($job, $arr, $queue);
        $this->success('操作完成', $test);
    }

    /**
     * 更新物流单
     * @param array params
     */
    public function fulfillmentTrack()
    {
        $fulfillment_track = table('fulfillment_track')
            ->where('status', 0)
            // ->where('name','#1321')
            ->limit(2)
            ->select();
        $returns = array();
        if (!empty($fulfillment_track)) {
            foreach ($fulfillment_track as $k => $v) {
                $return = array();
                $iscustom = table('fedition_accounturl')
                    ->where('id', $v['accounturl'])
                    ->find();
                //找订单
                $ordershopify = table('fedition_ordershopify')
                    ->where('name', $v['name'])
                    ->where('accounturl', $v['accounturl'])
                    ->find();

                if (!empty($iscustom) && !empty($ordershopify)) {
                    $data = array();
                    $orderfulfillments = table('fedition_orderfulfillments')
                        ->where('order_id', $ordershopify['id'])
                        ->find();
                    if (!empty($orderfulfillments) && !empty($orderfulfillments['tracking_ids'])) {
                        //修改
                        $data['fulfillment']['notify_customer'] = false;
                        $data['fulfillment']['tracking_info']['number'] = $v['number'];
                        $data['fulfillment']['tracking_info']['company'] = $v['company'];
                        $url = $iscustom['shopifyname'] . "/admin/api/2021-07/fulfillments/" . $orderfulfillments['tracking_ids'] . "/update_tracking.json";
                        $return = $this->posturl($url, $data, $iscustom);
                        $return = json_decode($return, true);
                    } else {
                        // 新增
                        $url2 = $iscustom['shopifyname'] . "/admin/api/2021-07/locations.json";
                        $data2 = $this->geturl($url2, $iscustom['shopifyapikey'], $iscustom['shopifysecretapikey']);
                        if (!empty($data2)) {
                            $data2 = json_decode($data2, true);
                            if (!empty($data2['locations'][0]['id']) && isset($data2['locations'][0]['id'])) {
                                $data['fulfillment']['location_id'] = $data2['locations'][0]['id'];
                            }
                        }
                        $data['fulfillment']['notify_customer'] = false;
                        $data['fulfillment']['tracking_number'] = $v['number'];
                        $data['fulfillment']['tracking_company'] = $v['company'];

                        $url3 = $iscustom['shopifyname'] . "/admin/api/2021-07/orders/" . $ordershopify['id'] . ".json";
                        $data3 = $this->geturl($url3, $iscustom['shopifyapikey'], $iscustom['shopifysecretapikey']);
                        if (!empty($data3)) {
                            $data3 = json_decode($data3, true);
                            if (isset($data3['order']['line_items']) && !empty($data3['order']['line_items'])) {
                                $line_itemss = $data3['order']['line_items'];
                                foreach ($line_itemss as $kdata3 => $vdata3) {
                                    $arrnn = array();
                                    $arrnn['id'] = $vdata3['id'];
                                    $data['fulfillment']['line_items'][] = $arrnn;
                                }
                                $url = $iscustom['shopifyname'] . "/admin/api/2021-07/orders/" . $ordershopify['id'] . "/fulfillments.json";
                                $return = $this->posturl($url, $data, $iscustom);
                                $return = json_decode($return, true);
                                if (!empty($return['errors']['base']['0'])) {
                                    //修改
                                    $data['fulfillment']['notify_customer'] = false;
                                    $data['fulfillment']['tracking_info']['number'] = $v['number'];
                                    $data['fulfillment']['tracking_info']['company'] = $v['company'];
                                    if (isset($data3['order']['fulfillments'][0]['id']) && !empty($data3['order']['fulfillments'][0]['id'])) {
                                        $url = $iscustom['shopifyname'] . "/admin/api/2021-07/fulfillments/" . $data3['order']['fulfillments'][0]['id'] . "/update_tracking.json";
                                        $return = $this->posturl($url, $data, $iscustom);
                                        $return = json_decode($return, true);
                                    }
                                }
                            }
                            // if(!empty($data2['locations'][0]['id']) && isset($data2['locations'][0]['id'])){
                            //     $data['fulfillment']['location_id'] = $data2['locations'][0]['id'];
                            // }
                        }
                    }

                    //1成功2失败
                    if (!empty($return['errors'])) {
                        $arrn['status'] = 2;
                        if (!empty($return['errors']['tracking_info']) && isset($return['errors']['tracking_info'])) {
                            $arrn['tracking_info'] = $return['errors']['tracking_info'];
                        }
                    } elseif (!empty($return['error'])) {
                        $arrn['status'] = 4;
                        $arrn['tracking_info'] = $return['error'];
                    } elseif (empty($return)) {
                        $arrn['status'] = 3;
                        $arrn['tracking_info'] = '空值';
                    } else {
                        $arrn['status'] = 1;
                    }
                    $returns[] = table('fulfillment_track')->where('id', $v['id'])->update($arrn);
                }
            }
        }
        $this->success('操作完成', $returns);
    }

    public function customers_timea($id = null)
    {
        if (!empty($id)) {
            $ordershopify = table('fedition_ordershopify')
                ->where('id', $id)
                ->select();
        } else {
            $where = array();
            $where['accounturl'] = 56;
            $ordershopify = table('fedition_ordershopify')
                ->order('customers_timea asc')
                ->where($where)
                ->limit('10')
                ->select();
        }
        $accountur = table('fedition_accounturl')
            ->where('id', 56)
            ->find();
        if (!empty($ordershopify)) {
            $row = array();
            foreach ($ordershopify as $t) {
                $url = $accountur['shopifyname'] . "/admin/api/2021-07/orders/" . $t['id'] . ".json";
                $data = $this->geturl($url, $accountur['shopifyapikey'], $accountur['shopifysecretapikey']);
                $data = json_decode($data, true);

                if (isset($data['order']['customer']['id']) && !empty($data['order']['customer']['id'])) {
                    if (!empty($data['order']['customer']['accepts_marketing'] === true)) {
                        $row['customers_timea'] = '888888888888';
                    } else {
                        $customer_id = $data['order']['customer']['id'];
                        $post['customer']['id'] = $customer_id;
                        $post['customer']['accepts_marketing'] = true;
                        $post['customer']['accepts_marketing_updated_at'] = '2022-07-23T15:32:56-04:00';
                        $url2 = $accountur['shopifyname'] . "/admin/api/2021-07/customers/" . $customer_id . ".json";
                        $data2 = $this->puturl($url2, $post, $accountur);
                        $data2 = json_decode($data2, true);
                        if (isset($data2['errors']) && !empty($data2['errors'])) {
                            $row['customers_timea'] = '99999999999';
                        } else {
                            $row['customers_timea'] = time();
                        }
                    }
                }
                table('fedition_ordershopify')
                    ->where('id', $t['id'])
                    ->update($row);
            }
            $this->success('操作成功');
        } else {
            $this->error('未找到相关订单');
        }
    }

    public function customers_timeb($id = null)
    {
        if (!empty($id)) {
            $ordershopify = table('leads')
                ->where('id', $id)
                ->select();
        } else {
            $where = array();
            // $where['accounturl'] = 57;
            $aid = $this->request->request('aid');
            $bid = $this->request->request('bid');
            $type = $this->request->request('type');
            $accounturl = $this->request->request('accounturl');
            if (!empty($aid) && !empty($bid)) {
                $where['id'] =  ['between', [$aid, $bid]];
            }
            if ($type == 1) {
                $where['customers_timea'] =  ['between', [0, 2]];
            }
            if ($type == 2) {
                $where['customers_timea'] =  '99999999999';
            }
            if (!empty($accounturl)) {
                $where['accounturl'] =  $accounturl;
            }
            $ordershopify = table('leads')
                ->order('customers_timea asc')
                ->where($where)
                ->limit('30')
                ->select();
        }
        if (!empty($ordershopify)) {
            $row = array();
            $returns = array();

            foreach ($ordershopify as $t) {
                $accountur = table('fedition_accounturl')
                    ->where('id', $t['accounturl'])
                    ->find();
                // $t['customer_id'] = '5844306067529';
                // $url = $accountur['shopifyname'] . "/admin/api/2021-07/customers/" . $t['customer_id'] . ".json";
                // $data = $this->geturl($url, $accountur['shopifyapikey'], $accountur['shopifysecretapikey']);
                // $data = json_decode($data, true);


                // $row['customers_timea'] = '1';
                // if (isset($data['customer']['id']) && !empty($data['customer']['id'])) {
                // if(!empty($data['customer']['accepts_marketing'] === true)){
                //     $row['customers_timea'] = '888888888888';
                // }else{
                $customer_id = $t['customer_id'];
                $post['customer']['id'] = $customer_id;
                $post['customer']['accepts_marketing'] = true;
                $post['customer']['verified_email'] = true;
                $post['customer']['accepts_marketing_updated_at'] = '2022-07-23T15:32:56-04:00';
                $url2 = $accountur['shopifyname'] . "/admin/api/2021-07/customers/" . $customer_id . ".json";
                $data2 = $this->puturl($url2, $post, $accountur);
                $data2 = json_decode($data2, true);
                // dump($data2);die;

                if (isset($data2['errors']) && !empty($data2['errors'])) {
                    $row['customers_timea'] = '99999999999';
                } else {
                    $row['customers_timea'] = time();
                }
                // }
                // } 
                $returns[] = table('leads')
                    ->where('id', $t['id'])
                    ->update($row);
            }
            $this->success('操作成功', $returns);
        } else {
            $this->error('未找到相关订单');
        }
    }

    public function puturl($url, $data = array(), $iscustom)
    {
        $data = (is_array($data)) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data;
        $apikey = $iscustom['shopifyapikey'];
        $secretapikey = $iscustom['shopifysecretapikey'];
        $headerArray = array("Content-Type:application/json;", 'Authorization:Basic ' . base64_encode("$apikey:$secretapikey"));
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); //设置请求方式
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * 增加sku 弃用
     * @param array params
     */
    public function z_productb()
    {
        $z_product = table('z_product')->select();
        $n_product = array();
        foreach ($z_product as $k => $v) {
            for ($i = 0; $i <= 4; $i++) {
                $arr = array();
                $arr['VariantPrice'] = $v['Variant Price'];
                if ($i == 0) {
                    $arr['Title'] = $v['Title'];
                    $arr['Body'] = $v['Body'];
                    $arr['Published'] = $v['Published'];
                    $arr['status'] = $v['status'];
                    $arr['GiftCard'] = $v['Gift Card'];
                    $arr['Option1Name'] = $v['Option1 Name'];
                    $arr['ImageSrc'] = $v['Image Src'];
                    $arr['ImagePosition'] = $v['Image Position'];
                    $arr['Option1Value'] = 'S';
                } else {
                    $arr['Title'] = '';
                    $arr['Body'] = '';
                    $arr['Published'] = '';
                    $arr['status'] = '';
                    $arr['GiftCard'] = '';
                    $arr['Option1Name'] = '';
                    $arr['ImageSrc'] = '';
                    $arr['ImagePosition'] = '';
                    switch ($i) {
                        case '1':
                            $arr['Option1Value'] = 'M';
                            break;
                        case '2':
                            $arr['Option1Value'] = 'L';
                            break;
                        case '3':
                            $arr['Option1Value'] = 'XL';
                            break;
                        case '4':
                            $arr['Option1Value'] = 'XXL';
                            break;
                        default:
                            $arr['Option1Value'] = 'XXXL';
                    }
                }
                $n_product[] = $arr;
            }
        }

        $a = table('z_productb')->insertAll($n_product);
        dump($a);
        die;
    }

    /**
     * api添加商品
     * @param array params
     */
    public function z_product_add()
    {
        $z_product = table('z_product_57')
            ->order('customers_timea asc')
            ->limit('20')
            ->select();
        $return = array();
        $iscustom = table('fedition_accounturl')
            ->where('id', '57')
            ->find();
        foreach ($z_product as $k => $v) {
            $row['customers_timea'] = time();
            $url = $iscustom['shopifyname'] . "/admin/api/2021-07/products.json";
            if (!empty($v['Title']) && empty($v['customers_timea'])) {
                $data['product']['title'] = $v['Title'];
                $data['product']['body_html'] = $v['Body'];
                $data['product']['vendor'] = ''; //供应商

                $data['product']['status'] = $v['status'];


                $sku1 = '';
                $fenlei = table('z_product_fenlei57')->where('pid', $v['pid'])->find();
                if (!empty($fenlei)) {
                    $data['product']['product_type'] = $fenlei['leibie2'];
                    $data['product']['tags'] = $fenlei['leibie1'] . '&' . $fenlei['leibie2'];
                    $sku1 = $fenlei['leibie1'] . '-' . $fenlei['leibie2'] . '-' . $v['id'];
                } else {
                    $data['product']['product_type'] = ''; //产品分类
                    $data['product']['tags'] = '';
                    $sku1 = '';
                }

                $data['product']['variants'][0]['option1'] = 'S';
                $data['product']['variants'][0]['price'] = $v['new_Price'];
                $data['product']['variants'][0]['sku'] = $sku1 . '-M';
                $data['product']['variants'][1]['option1'] = 'M';
                $data['product']['variants'][1]['price'] = $v['new_Price'];
                $data['product']['variants'][1]['sku'] = $sku1 . '-L';
                $data['product']['variants'][2]['option1'] = 'L';
                $data['product']['variants'][2]['price'] = $v['new_Price'];
                $data['product']['variants'][2]['sku'] = $sku1 . '-XL';
                $data['product']['variants'][3]['option1'] = 'XL';
                $data['product']['variants'][3]['price'] = $v['new_Price'];
                $data['product']['variants'][3]['sku'] = $sku1 . '-XXL';
                $data['product']['variants'][4]['option1'] = 'XXL';
                $data['product']['variants'][4]['price'] = $v['new_Price'];
                $data['product']['variants'][4]['sku'] = $sku1 . '-XXXL';
                $data['product']['variants'][5]['option1'] = 'XXXL';
                $data['product']['variants'][5]['price'] = $v['new_Price'];
                $data['product']['variants'][5]['sku'] = $sku1 . '-4XL';
                $data['product']['variants'][6]['option1'] = '4XL';
                $data['product']['variants'][6]['price'] = $v['new_Price'];
                $data['product']['variants'][6]['sku'] = $sku1 . '-5XL';

                $data['product']['options'][0]['name'] = 'size';
                $data['product']['options'][0]['values'][0] = 'S';
                $data['product']['options'][0]['values'][1] = 'M';
                $data['product']['options'][0]['values'][2] = 'L';
                $data['product']['options'][0]['values'][3] = 'XL';
                $data['product']['options'][0]['values'][4] = 'XXL';
                $data['product']['options'][0]['values'][5] = 'XXXL';
                $data['product']['options'][0]['values'][6] = '4XL';
                $data['product']['images'][0]['src'] = $v['Image Src'];

                if (!empty($sku1)) {
                    $return = $this->posturl($url, $data, $iscustom);
                } else {
                    $return = array();
                }

                if (!empty($return)) {
                    $datareturn = json_decode($return, true);
                    if (isset($datareturn['product']['id']) && !empty($datareturn['product']['id'])) {
                        $row['product_id'] = $datareturn['product']['id'];
                        $row['handle'] = $datareturn['product']['handle'];
                    } else {
                        $row['customers_timea'] = '111111';
                    }
                }
            }
            table('z_product_57')
                ->where('id', $v['id'])
                ->update($row);
        }
        $this->success('操作成功');
    }

    /**
     * api修改商品
     * @param array params
     */
    public function z_product_edit()
    {
        $z_product = table('z_product_59')
            //修改价格-1
            ->where('customers_timea', '222')
            //修改价格-1
            ->order('customers_timea asc')
            ->limit('30')
            ->select();
        $return = array();
        $iscustom = table('fedition_accounturl')
            ->where('id', '59')
            ->find();
        foreach ($z_product as $k => $v) {
            $row['customers_timea'] = '2222';
            $url = $iscustom['shopifyname'] . "/admin/api/2021-07/products/" . $v['product_id'] . ".json";
            if (!empty($v['status']) && !empty($v['Title'])) {
                $data['product']['id'] = $v['product_id'];
                $data['product']['vendor'] = 'top';
                //修改价格-2
                $data['product']['status'] = $v['status'];
                if (!empty($v['new_Price'])) {
                    $data['product']['variants'][0]['option1'] = 'S';
                    $data['product']['variants'][0]['price'] = $v['new_Price'];
                    $data['product']['variants'][0]['sku'] = 'wtop001-m';
                    $data['product']['variants'][1]['option1'] = 'M';
                    $data['product']['variants'][1]['price'] = $v['new_Price'];
                    $data['product']['variants'][1]['sku'] = 'wtop001-l';
                    $data['product']['variants'][2]['option1'] = 'L';
                    $data['product']['variants'][2]['price'] = $v['new_Price'];
                    $data['product']['variants'][2]['sku'] = 'wtop001-xl';
                    $data['product']['variants'][3]['option1'] = 'XL';
                    $data['product']['variants'][3]['price'] = $v['new_Price'];
                    $data['product']['variants'][3]['sku'] = 'wtop001-xxl';
                    $data['product']['variants'][4]['option1'] = 'XXL';
                    $data['product']['variants'][4]['price'] = $v['new_Price'];
                    $data['product']['variants'][4]['sku'] = 'wtop001-xxxl';
                } else {
                    $data['product']['variants'][0]['option1'] = 'S';
                    $data['product']['variants'][0]['price'] = $v['Variant Price'];
                    $data['product']['variants'][0]['sku'] = 'wtop001-m';
                    $data['product']['variants'][1]['option1'] = 'M';
                    $data['product']['variants'][1]['price'] = $v['Variant Price'];
                    $data['product']['variants'][1]['sku'] = 'wtop001-l';
                    $data['product']['variants'][2]['option1'] = 'L';
                    $data['product']['variants'][2]['price'] = $v['Variant Price'];
                    $data['product']['variants'][2]['sku'] = 'wtop001-xl';
                    $data['product']['variants'][3]['option1'] = 'XL';
                    $data['product']['variants'][3]['price'] = $v['Variant Price'];
                    $data['product']['variants'][3]['sku'] = 'wtop001-xxl';
                    $data['product']['variants'][4]['option1'] = 'XXL';
                    $data['product']['variants'][4]['price'] = $v['Variant Price'];
                    $data['product']['variants'][4]['sku'] = 'wtop001-xxxl';
                }
                //修改价格-2
                $return = $this->puturl($url, $data, $iscustom);
                if (!empty($return)) {
                    $datareturn = json_decode($return, true);
                    if (isset($datareturn['product']['id']) && !empty($datareturn['product']['id'])) {
                        $row['customers_timea'] = time();
                        $row['handle'] = $datareturn['product']['handle'];
                    } else {
                        $row['customers_timea'] = '111111';
                    }
                }
            }
            table('z_product_59')
                ->where('id', $v['id'])
                ->update($row);
        }
        $this->success('操作成功');
    }


    /**
     * api修改商品
     * @param array params
     */
    public function z_product_edit2()
    {
        $z_product = table('products_shopify')
            ->where('accounturl', '70')
            ->order('customers_timea asc')
            ->limit('30')
            ->select();
        $return = array();
        $iscustom = table('fedition_accounturl')
            ->where('id', '70')
            ->find();
        foreach ($z_product as $k => $v) {
            $row['customers_timea'] = '2222';
            $url = $iscustom['shopifyname'] . "/admin/api/2021-07/products/" . $v['id'] . ".json";
            if (!empty($v['status']) && !empty($v['title'])) {
                $data['product']['id'] = $v['id'];
                $data['product']['vendor'] = 'belleloving';
                $return = $this->puturl($url, $data, $iscustom);
                if (!empty($return)) {
                    $datareturn = json_decode($return, true);
                    if (isset($datareturn['product']['id']) && !empty($datareturn['product']['id'])) {
                        $row['customers_timea'] = time();
                    } else {
                        $row['customers_timea'] = '111111';
                    }
                }
            }
            table('products_shopify')
                ->where('id', $v['id'])
                ->update($row);
        }
        $this->success('操作成功');
    }

    /**
     * api重组评论以及商品id
     * @param array params
     */
    public function z_product_comments()
    {
        $z_product = table('z_product_comments56')
            ->order('customers_timea asc')
            ->limit('1000')
            ->select();
        $return = array();
        foreach ($z_product as $k => $v) {
            $iscustom = table('z_product_56')
                ->where('url', $v['url'])
                ->find();
            if (!empty($iscustom)) {
                $update['customers_timea'] = time();
                $update['Title'] = $iscustom['Title'];
                $update['ImageSrc'] = $iscustom['Image Src'];
                $update['product_id'] = $iscustom['product_id'];
                $update['handle'] = $iscustom['handle'];
                // $update['handleurl'] = $iscustom['handleurl'];
                $return[] = table('z_product_comments56')
                    ->where('id', $v['id'])
                    ->update($update);
            }
        }
        $this->success('操作成功', $return);
    }

    /**
     * api新增图片
     * @param array params
     */
    public function z_product_image()
    {
        $z_product = table('z_product_image')
            ->order('customers_timea asc')
            ->limit('5')
            ->select();
        $return = array();
        foreach ($z_product as $k => $v) {
            $iscustom = table('z_product_56')
                ->where('url', $v['url'])
                ->find();
            if (!empty($iscustom) && empty($v['customers_timea'])) {
                $new = $this->new_infos($v, $iscustom);
                if (!empty($new)) {
                    table('z_product_images56')->insertAll($new);
                }
            }
            $updates['customers_timea'] = time();
            $return[] = table('z_product_image')
                ->where('id', $v['id'])
                ->update($updates);
        }
        $this->success('操作成功', $return);
    }

    /**
     * 方法详情
     * @param array params
     */
    public function new_infos($v, $iscustom)
    {
        $update['product_id'] = $iscustom['product_id'];
        $new = array();
        // if(!empty($v['img1'])){
        //     $update['img'] = $this->new_images($v['img1']);
        //     if(!empty($update['img'])){
        //         $new[] = $update;
        //     }
        // }
        if (!empty($v['img2'])) {
            $update['img'] = $this->new_images($v['img2']);
            if (!empty($update['img'])) {
                $new[] = $update;
            }
        }
        if (!empty($v['img3'])) {
            $update['img'] = $this->new_images($v['img3']);
            if (!empty($update['img'])) {
                $new[] = $update;
            }
        }
        if (!empty($v['img4'])) {
            $update['img'] = $this->new_images($v['img4']);
            if (!empty($update['img'])) {
                $new[] = $update;
            }
        }
        if (!empty($v['img5'])) {
            $update['img'] = $this->new_images($v['img5']);
            if (!empty($update['img'])) {
                $new[] = $update;
            }
        }
        if (!empty($v['img6'])) {
            $update['img'] = $this->new_images($v['img6']);
            if (!empty($update['img'])) {
                $new[] = $update;
            }
        }
        return $new;
    }

    /**
     * 方法详情
     * @param array params
     */
    public function new_images($img)
    {
        $imgs = explode('?v=', $img);
        if (!empty($imgs[0])) {
            return $imgs[0];
        } else {
            return 0;
        }
    }

    /**
     * api新增图片
     * @param array params
     */
    public function z_product_images()
    {
        $z_product = table('z_product_images56')
            ->order('customers_timea asc')
            ->limit('10')
            ->select();
        $iscustom = table('fedition_accounturl')
            ->where('id', '56')
            ->find();
        $returns = array();
        foreach ($z_product as $k => $v) {
            $update['customers_timea'] = '222';
            $url = $iscustom['shopifyname'] . "/admin/api/2021-07/products/" . $v['product_id'] . "/images.json";
            if (!empty($v['img']) && empty($v['customers_timea'])) {
                $data['image']['src'] = $v['img'];
                $return = $this->posturl($url, $data, $iscustom);
                if (!empty($return)) {
                    $datareturn = json_decode($return, true);
                    if (isset($datareturn['image']['id']) && !empty($datareturn['image']['id'])) {
                        $update['customers_timea'] = time();
                    } else {
                        $update['customers_timea'] = '111111';
                    }
                }
            }
            $returns[] = table('z_product_images56')
                ->where('id', $v['id'])
                ->update($update);
        }
        $this->success('操作成功', $returns);
    }

    /**
     * 下载图片
     * @param array params
     */
    public function z_product_imagesb()
    {
        $z_product = table('z_product_images56')
            ->order('customers_timeb asc')
            ->limit('4')
            ->select();
        $this->success('操作成功', $z_product);
        $returns = array();
        foreach ($z_product as $k => $v) {
            $products = table('z_product_56')->where('product_id', $v['product_id'])->find();
            $update['customers_timeb'] = '222';
            if (!empty($products)) {
                $url = $v['img'];
                $products2 = explode('/', $products['Title']);
                $save_dir = 'D:\yile\\' . $products2['0'];
                $img2 = explode('products/', $v['img']);
                $filename = $img2[1];
                $return = $this->download($url, $save_dir, $filename, 0);
                if ($return['error'] == 0) {
                    $update['customers_timeb'] = time();
                } else {
                    $update['customers_timeb'] = '111111';
                }
            }
            $returns[] = table('z_product_images56')
                ->where('id', $v['id'])
                ->update($update);
        }
        $this->success('操作成功', $returns);
    }


    public function download($url, $save_dir, $filename, $type)
    {
        // 路径是否为空
        if (trim($url) == '') {
            return array('file_name' => '', 'save_path' => '', 'error' => 1);
        }
        //保存到
        // if(trim($save_dir)==''){
        //     $save_dir='./img';
        // }
        // if(trim($filename)==''){//保存文件名
        //     $ext=strrchr($url,'.');
        //     //判断后缀是否合法
        //     if($ext!='.gif' && $ext!='.jpeg' && $ext!='.jpg'){
        //         return array('file_name'=>'','save_path'=>'','error'=>3);
        //     }
        //     //生成文件名字
        //     $filename=time().$ext;
        // }
        if (0 !== strrpos($save_dir, '/')) {
            $save_dir .= '/';
        }

        //创建保存目录
        if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
            return array('file_name' => '', 'save_path' => '', 'error' => 5);
        }
        //获取远程文件所采用的方法
        if ($type) {
            $ch = curl_init();
            $timeout = 5;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $img = curl_exec($ch);
            curl_close($ch);
        } else {
            ob_start();
            readfile($url);
            $img = ob_get_contents();
            ob_end_clean();
        }
        //$size=strlen($img);
        //文件大小
        $fp2 = @fopen($save_dir . $filename, 'a');
        fwrite($fp2, $img);
        fclose($fp2);
        unset($img, $url);
        return array('file_name' => $filename, 'save_path' => $save_dir . $filename, 'error' => 0);
    }
    /**
     *
     */
    // public function z_product_hidden()
    // {
    //     $z_product = table('z_product_hidden')
    //     ->select();
    //     $return = array();
    //     $num = 0;
    //     foreach ($z_product as $k=>$v) {
    //         $iscustom = table('z_product')
    //             ->where('url', $v['url'])
    //             ->find();
    //         if(!empty($iscustom)){
    //             $num += 1;
    //             $update['status'] = 'hidden';
    //             table('z_product')
    //                 ->where('id',$iscustom['id'])
    //                 ->update($update);
    //         }else{
    //             $return[] = $v['url'];
    //         }
    //     }
    //     $this->success('操作成功'.$num,$return);
    // }

    // public function z_product_cha()
    // {
    //     $z_product = table('z_product')
    //     ->order('customers_timea asc')
    //     ->limit('50')
    //     ->select();
    //     $return = array();
    //     $iscustom = table('fedition_accounturl')
    //         ->where('id', '57')
    //         ->find();
    //     foreach ($z_product as $k=>$v) {
    //         $row['customers_timea'] = time();
    //         $url = $iscustom['shopifyname']."/admin/api/2021-07/products/".$v['product_id'].".json";
    //         if(!empty($v['Title']) && empty($v['customers_timea'])){
    //             $return = $this->geturl($url,$iscustom['shopifyapikey'],$iscustom['shopifysecretapikey']);
    //             if(!empty($return)){
    //                 $datareturn = json_decode($return, true);
    //                 if(isset($datareturn['product']['handle']) && !empty($datareturn['product']['handle'])){
    //                     $row['handle'] = $datareturn['product']['handle'];
    //                     $row['handleurl'] = 'https://freelywear.com/products/'.$row['handle'];
    //                 }else{
    //                     $row['customers_timea'] = '111111';
    //                 }
    //             } 
    //         }
    //         table('z_product')
    //             ->where('id', $v['id'])
    //             ->update($row);
    //     }
    //     $this->success('操作成功');
    // }

    /**
     * 方法详情
     * @param array params
     */
    public function test1()
    {
        $aaa = table('aaaaaaaa')->select();
        $aa = array();
        if (!empty($aaa)) {
            foreach ($aaa as $k => $v) {
                $bbb = table('fedition_ordershopify')->where('id', $v['h'])->find();
                if (!empty($bbb)) {
                    $update['f'] = $bbb['freight'];
                    $update['g'] = $bbb['material'];
                    $update['e'] = $bbb['tracking_number'];
                    $update['d'] = $bbb['total_price'];
                    $aa[] = table('aaaaaaaa')->where('id', $v['id'])->update($update);
                }
            }
        }
        dump($aa);
        die;
    }

    public function teshu2()
    {
        $ordersku = table('aaaaaaaa')->select();
        foreach ($ordersku as $k => $v) {
            $row['updatetimes'] = '222';
            table('fedition_ordersku')->where('id', $v['a'])->update($row);
        }
    }

    public function teshu()
    {
        $where['accounturl']  = array('egt', 56);
        $ordersku = table('fedition_ordersku')
            ->where($where)
            ->order('updatetimes asc')
            ->limit(2000)->select();
        foreach ($ordersku as $k => $v) {
            $row['updatetimes'] = time();
            $row['skun'] = preg_replace('|[0-9a-zA-Z/]+|', '', $v['sku']);
            table('fedition_ordersku')->where('id', $v['id'])->update($row);
        }
    }

    /**
     * 判断是否存在特殊字符，可判断中英文及特殊符号混合串
     * 存在返回true
     * @param string $str
     * @return boolean
     */
    function has_special_str($str)
    {
        //$前要加反斜杠
        $specialChars = "~·`!！@#\$￥%^…&*()（）—-_=+[]{}【】、|\\;:；：'\"“‘,./<>《》?？，。";
        //特殊符号数组
        $specialArr = array();
        $len = mb_strlen($specialChars, 'UTF-8');
        for ($i = 0; $i < $len; $i++) {
            $specialArr[] = mb_substr($specialChars, $i, 1, 'UTF-8');
        }
        //待比较字符串数组
        $arr = array();
        $len = mb_strlen($str, 'UTF-8');
        for ($i = 0; $i < $len; $i++) {
            $arr[] = mb_substr($str, $i, 1, 'UTF-8');
        }
        foreach ($arr as $v) {
            if (in_array($v, $specialArr)) {
                return true;
            }
        }
        return false;
    }


    public function testa()
    {
        $ordersku = table('aaaaaaaa')
            ->order('d asc')
            ->limit(1000)
            ->select();

        foreach ($ordersku as $k => $v) {
            $where = array();
            $where['fulfillment_status'] = 'fulfilled';
            $line_item = array();
            if (!empty($v['a'])) {
                $line_item['tracking_company'] = '4PX';
                $line_item['tracking_number'] = $v['a'];
                $ordershopify = $this->openpx2($line_item);
            }

            if ($ordershopify == 0) {
                $data['c'] = '000';
            } else {
                $data['c'] = $ordershopify;
            }
            $data['d'] = time();
            $ordersku = table('aaaaaaaa')
                ->where('id', $v['id'])
                ->update($data);
        }
    }

    public function openpx2($line_item)
    {
        $return = 0;
        //4PX
        if ($line_item['tracking_company'] == '4PX' && !empty($line_item['tracking_number'])) {
            $yapp_key = '15e7e7b7-f23a-4e00-a9f8-cba67091206a';
            $yformat = 'json';
            $ymethod = 'tr.order.tracking.get';
            list($msec, $sec) = explode(' ', microtime());
            $ytimestamp = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
            $yv = '1.0';
            $app_key = 'app_key' . $yapp_key;
            $format = 'format' . $yformat;
            $method = 'method' . $ymethod;
            $timestamp = 'timestamp' . $ytimestamp;
            $v = 'v' . $yv;
            $data['deliveryOrderNo'] = $line_item['tracking_number'];
            $body = json_encode($data);
            $appSecret = 'f767bd69-f011-43df-b168-f48ff80e8967';
            $sign = $app_key . '' . $format . '' . $method . '' . $timestamp . '' . $v . '' . $body . '' . $appSecret;
            $sign = md5($sign);
            //测试环境
            //            $url = 'http://open.sandbox.4px.com/router/api/service';
            //正式环境
            $url = 'http://open.4px.com/router/api/service';
            $url = $url . '?method=' . $ymethod . '&app_key=' . $yapp_key . '&v=' . $yv . '&timestamp=' . $ytimestamp . '&format=' . $yformat . '&sign=' . $sign;
            $data = $this->posturlopenpx($url, $data);
            $data = json_decode($data, true);

            if (!empty($data['data'])) {
                $msg = $data['data']['trackingList'][0]['trackingContent'];
                $return = $msg;
            }
        }
        return $return;
    }

    /**
     * getfeditionorderquantity
     * @param array params
     */
    public function getfeditionorderquantity()
    {
        $limitOffset = $this->request->request('limitOffset');
        $limitLength = $this->request->request('limitLength');
        $time1 = $this->request->request('time1');
        $time2 = $this->request->request('time2');
        if (!isset($limitOffset)) {
            $limitOffset = 0;
        }
        if (empty($limitLength) || empty($time1) || empty($time2)) {
            $lists = array();
            $this->success('操作成功', $lists);
        }
        $where_shopify['b.financial_status'] = array('in', 'paid,refunded,partially_refunded');
        $where_shopify['b.ismaterial'] = array('in', '0,3');
        $where_shopify['b.created_at'] =  ['between', [$time1, $time2]];
        $where2['accounturl']  = array('egt', 56);
        $where2['a.product_id']  = array('egt', 1);
        $lists = table('fedition_orderquantity')
            ->field("a.*,b.accounturl,b.name as order_name")
            ->alias('a')
            ->join('fa_fedition_ordershopify b', 'b.id = a.order_id', 'left')
            ->join('fa_fedition_accounturl c', 'b.accounturl = c.id', 'left')
            ->where($where2)
            ->where($where_shopify)
            ->group('a.product_id')
            ->order('b.accounturl', 'desc')
            ->order('a.product_id', 'desc')
            ->limit($limitOffset, $limitLength)
            ->select();
        $lists2 = array();
        foreach ($lists as $k => $v) {
            $v['zmaterial'] = 0;
            $accounturl = table('fedition_accounturl')->where('id', '=', $v['accounturl'])->find();
            if ($accounturl) {
                $v['accounturl_name'] = $accounturl['name'];
            } else {
                $v['accounturl_name'] = '店铺名称已删除';
            }
            $admin = table('admin')->where('id', '=', $accounturl['admin_id'])->find();
            if ($admin) {
                $v['admin_name'] = $admin['nickname'];
            } else {
                $v['admin_name'] = '管理员未设置';
            }
            if (!empty($v['product_id'])) {
                $v['quantitys'] = table('fedition_orderquantity')->where('product_id', $v['product_id'])->sum('quantity');
                $orderproduct = table('fedition_orderproduct')->where('product_id', $v['product_id'])->find();
                if (!empty($orderproduct)) {
                    $orderskus = table('fedition_ordersku')->where('product_id', $orderproduct['product_id'])->find();
                    if (!empty($orderskus)) {
                        $v['zmaterial'] = $orderskus['material'];
                    }
                    $v['product_images'] = $orderproduct['product_images'];
                    $v['handle_url'] = $orderproduct['handle_url'];
                }
            }
            $lists2[] = $v;
        }
        $this->success('操作成功', $lists2);
    }


    public function getfeditionorderquantitycount()
    {
        $time1 = $this->request->request('time1');
        $time2 = $this->request->request('time2');
        if (empty($time1) || empty($time2)) {
            $sku_arr = 0;
            $this->success('操作成功', $sku_arr);
        }
        $where_shopify['b.financial_status'] = array('in', 'paid,refunded,partially_refunded');
        $where_shopify['b.ismaterial'] = array('in', '0,3');
        $where_shopify['b.created_at'] =  ['between', [$time1, $time2]];
        $where2['accounturl']  = array('egt', 56);
        $where2['a.product_id']  = array('egt', 1);
        $sku_arr = table('fedition_orderquantity')
            ->field("a.*,b.accounturl,b.name as order_name")
            ->alias('a')
            ->join('fa_fedition_ordershopify b', 'b.id = a.order_id', 'left')
            ->join('fa_fedition_accounturl c', 'b.accounturl = c.id', 'left')
            ->where($where2)
            ->where($where_shopify)
            ->group('a.product_id')
            ->count();
        $this->success('操作成功', $sku_arr);
    }


    /**
     * 报表
     * @param array params
     */
    public function add_report()
    {
        $accounturl = $this->request->request('accounturl');
        $iscustom2 = table('fedition_accounturl')
            ->where('id', $accounturl)
            ->find();
        $addreport['name'] = 'test report';
        $addreport['shopify_ql'] = 'SHOW total_sales BY order_id FROM sales SINCE -30d UNTIL today ORDER BY total_sales';
        $newdata['report'] = $addreport;
        $url2 = $iscustom2['shopifyname'] . "/admin/api/2021-07/reports.json";
        $newreturn = $this->posturl($url2, $newdata, $iscustom2);
        dump($newreturn);
        die;

        if (!empty($newreturn)) {
            $datareturn = json_decode($newreturn, true);
            if (isset($datareturn['product']['id']) && !empty($datareturn['product']['id'])) {
                $msgs = $datareturn['product']['id'];
            }
        }
    }


    // 按天统计运营情况
    public function days_statistical_test()
    {
        $where['timedate'] = '1669824000';
        $where['user'] = 37;
        $zyeji = table('zyeji')
            ->field("user,accounturl_name,date_of,currency,SUM(`total_price`) as total_price,SUM(`freight`) as freight,SUM(`material`) as material,SUM(`total_tip_received`) as total_tip_received,SUM(`total_shipping_price_set`) as total_shipping_price_set,SUM(`current_subtotal_price`) as current_subtotal_price")
            ->where($where)
            ->group('accounturl_name,date_of')
            ->select();
        dump($zyeji);
        die;
    }

    /**
     * 方法详情
     * @param array params
     */
    public function fedition_ordershopify_last()
    {
        $where['status'] = 'unfulfilled';
        $fedition_ordershopify_last = table('fedition_ordershopify_last')->where($where)->select();
        if (!empty($fedition_ordershopify_last)) {
            foreach ($fedition_ordershopify_last as $k => $v) {
                $data1['status'] = 'error';
                $where2['name'] = $v['name'];
                $where2['accounturl'] = $v['accounturl'];
                $fedition_ordershopify = table('fedition_ordershopify')->where($where2)->find();
                if (!empty($fedition_ordershopify)) {

                    $accountur = table('fedition_accounturl')
                        ->where('id', $v['accounturl'])
                        ->find();
                    $url = $accountur['shopifyname'] . "/admin/api/2021-07/orders/" . $fedition_ordershopify['id'] . ".json";
                    $data = $this->geturl($url, $accountur['shopifyapikey'], $accountur['shopifysecretapikey']);
                    $data = json_decode($data, true);

                    if (isset($data['order'])) {
                        $data1['fulfillment_status'] = $data['order']['fulfillment_status'];
                        $data1['financial_status'] = $data['order']['financial_status'];
                    }
                    $data1['status'] = 'success';
                }
                table('fedition_ordershopify_last')
                    ->where('id', $v['id'])
                    ->update($data1);
            }
        }
        $this->success('操作成功');
    }


    /**
     * 给产品批量添加元字段
     * @param array params
     */
    public function put_metafields_product()
    {
        $products_shopify = table('products_shopify')
            ->order('updateordertime asc')
            ->where('updatestatus', 'hidden')
            ->limit('2')
            ->select();
        $return_shopify = array();
        if (!empty($products_shopify)) {
            $data1['updatestatus'] = 'unavailable';
            foreach ($products_shopify as $k => $v) {

                //先更新
                $iscustom = table('fedition_accounturl')
                    ->where('id', $v['accounturl'])
                    ->find();
                $url = $iscustom['shopifyname'] . "/admin/api/2021-07/products/" . $v['id'] . ".json";
                $ldata = $this->geturl($url, $iscustom['shopifyapikey'], $iscustom['shopifysecretapikey']);

                if ($ldata) {
                    $ldata2 = json_decode($ldata, true);
                    if (!empty($ldata2['product'])) {
                        $lproduct = $ldata2['product'];
                        $data1['title'] = $lproduct['title'];
                        $data1['product_type'] = $lproduct['product_type'];
                    }
                }

                if (!empty($data1['title'])) {
                    $url = $iscustom['shopifyname'] . "/admin/api/2023-01/products/" . $v['id'] . ".json";
                    $newdata = array();
                    $newdata['product']['id'] = $v['id'];
                    $metafields['key'] = '_sku';
                    $metafields['value'] = $data1['title'];
                    $metafields['type'] = 'single_line_text_field';
                    $metafields['namespace'] = 'api';
                    $newdata['product']['metafields'][] = $metafields;
                    $data1['metafields'] = $metafields['value'];
                    $newreturn = $this->puturl($url, $newdata, $iscustom);
                    if (!empty($newreturn)) {
                        $datareturn = json_decode($newreturn, true);
                        if (isset($datareturn['product']['id']) && !empty($datareturn['product']['id'])) {
                            $data1['updatestatus'] = 'normal';
                        }
                    }
                }
                $data1['updateordertime'] = time();
                $return_shopify = table('products_shopify')
                    ->where('id', $v['id'])
                    ->update($data1);
            }
        }
        $this->success('操作成功', $return_shopify);
    }

    // http://121.5.76.151:100/Api/Myshopify/shop_edit?id=59&accounturl=87
    public function shop_edit()
    {
        $id = $this->request->request('id');
        $accounturl = $this->request->request('accounturl');
        $return = $this->accounturl_product3($id, $accounturl);
        $arr['transfer_time'] = time();
        if ($return == 3) {
            $arr['transfer_status'] = 2;
        } else {
            $arr['transfer_status'] = 1;
        }
        $return = table('products_shopify')
            ->where('id', $id)
            ->update($arr);
        $this->success('操作成功', $return);
    }

    /**
     * SKU排行
     * @param array params
     */
    public function sku_ranking()
    {
        // dump(strtolower(str_replace(' ', '', ' bra_beige_ 3xl ')));
        // die;
        //计算当月时间0点
        $redis = new Redis();

        //前端会传undefined
        if ($this->request->request('start_time') == 'undefined') {
            $firstday = strtotime(date('Y-m-01'));
        }
        if ($this->request->request('end_time') == 'undefined') {
            $lastday = time();
        }
        //前端会传undefined 结束
        if ($this->request->request('start_time') !== 'undefined') {
            $firstday = $this->request->request('start_time') ? strtotime($this->request->request('start_time')) : strtotime(date('Y-m-01'));
        }
        if ($this->request->request('end_time') !== 'undefined') {
            $lastday = $this->request->request('end_time') ? strtotime($this->request->request('end_time')) : time();
        }
        $accounturl = $this->request->request('accounturl');
        if (empty($accounturl)) {
            $statistics = $redis->get('sku_ranking-' . $firstday . '-' . $lastday);
            if (empty($statistics)) {
                $sql = "SELECT 
                    c.sku,
                    sum(b.quantity) as count,
                    b.title,
                    d.name,
                    e.handle_url,
                    b.product_id,
                    c.variants_id as SKUid
                    FROM fa_fedition_ordershopify as a
                    LEFT JOIN fa_fedition_orderquantity as b ON a.id=b.order_id
                    LEFT JOIN fa_fedition_ordersku as c ON b.variant_id=c.variants_id
                    LEFT JOIN fa_fedition_accounturl as d ON a.accounturl=d.id
                    LEFT JOIN fa_fedition_orderproduct as e ON b.product_id=e.product_id
                    where a.financial_status = 'paid'
                    AND a.created_at >= " . $firstday . "
                    AND a.created_at <= " . $lastday . "
                    AND (a.accounturl = '81' or a.accounturl = '79' or a.accounturl = '59')
                    AND c.id > 1
                    GROUP BY SKUid
                    ORDER BY count DESC
                ";
                $statistics = Db::query($sql);
                $redis->set('sku_ranking-' . $firstday . '-' . $lastday, $statistics, 3600 * 7);
            }
        } else {
            $statistics = $redis->get('sku_ranking-' . $firstday . '-' . $lastday . '-' . $accounturl);
            if (empty($statistics)) {
                $sql = "SELECT 
                    c.sku,
                    sum(b.quantity) as count,
                    b.title,
                    d.name,
                    e.handle_url,
                    b.product_id,
                    c.variants_id as SKUid
                    FROM fa_fedition_ordershopify as a
                    LEFT JOIN fa_fedition_orderquantity as b ON a.id=b.order_id
                    LEFT JOIN fa_fedition_ordersku as c ON b.variant_id=c.variants_id
                    LEFT JOIN fa_fedition_accounturl as d ON a.accounturl=d.id
                    LEFT JOIN fa_fedition_orderproduct as e ON b.product_id=e.product_id
                    where a.accounturl = " . $accounturl . "
                    AND a.financial_status = 'paid'
                    AND a.created_at >= " . $firstday . "
                    AND a.created_at <= " . $lastday . "
                    AND c.id > 1
                    GROUP BY SKUid
                    ORDER BY count DESC
                ";
                $statistics = Db::query($sql);
                $redis->set('sku_ranking-' . $firstday . '-' . $lastday . '-' . $accounturl, 3600 * 7);
            }
        }

        foreach ($statistics as $k => $v) {
            if (strstr($v['sku'], 'bra01') != false || strstr($v['sku'], 'bra04') != false || strstr($v['sku'], 'bra10') != false) {
                $statistics1[] = $v;
            }
        }

        if (empty($statistics1)) {
            $this->error('暂无数据');
        };
        // $statistics = [
        //     ['sku' => 'bra10-Black+Nude-44E-1', 'count' => 1], //2
        //     ['sku' => 'bra10-Black+Nude-34E-2', 'count' => 2], //8
        //     ['sku' => 'bra10-Black+Nude-48C-3', 'count' => 3], //18
        //     ['sku' => 'bra10-Black+Nude-44E-3', 'count' => 4], //24
        // ];
        $merge_sku = getsku();

        foreach ($statistics1 as $v) {
            $multiple = 1;
            $sku_title_arr =  explode('-', strtolower(str_replace(' ', '', $v['sku'])));
            file_put_contents('1.txt', $v['sku']);
            if (isset($sku_title_arr[0])) {
                if (isset($sku_title_arr[1])) {
                    if (isset($sku_title_arr[3])) {
                        $multiple = $sku_title_arr[3];
                    }
                    $sku_title_arr1 =  explode('+', $sku_title_arr[1]);
                    foreach ($sku_title_arr1 as $vl) {
                        $merge_sku[$sku_title_arr[0]] = $merge_sku[$sku_title_arr[0]] + $v['count'] * $multiple;
                        $merge_sku[$sku_title_arr[0] . '_' . $vl] = $merge_sku[$sku_title_arr[0] . '_' . $vl] + $v['count'] * $multiple;
                        if (isset($sku_title_arr[2])) {
                            $merge_sku[$sku_title_arr[0] . '_' . $vl . '_' . $sku_title_arr[2]] = $merge_sku[$sku_title_arr[0] . '_' . $vl . '_' . $sku_title_arr[2]]  + $v['count'] * $multiple;
                        }
                    }
                }
            }
        }
        foreach ($merge_sku as $k => $v) {
            if ($v == 0) {
                unset($merge_sku[$k]);
            }
        }
        foreach ($merge_sku as $k => $v) {
            $merge_sku_new[] =
                ['sku' => $k, 'count' => $v];
        }
        ob_end_clean();
        //2.导入PHPExcel类库
        vendor("PHPExcel.PHPExcel");
        vendor("PHPExcel.PHPExcel.IOFactory");
        vendor("PHPExcel.PHPExcel.Writer.Excel2007");

        //3.查询出数据库数据


        //4.实例化PHPExcel对象
        /**  
         * 实例化之后的PHPExcel对象类似于一个暂存于内存中文档文件，  
         * 可以对它进行操作以达到修改文档数据的目的 
         */
        $objPHPExcel = new \PHPExcel(); //通过new关键字创建空白文档  

        $PHPWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel); //用于2007版本格式

        //5.设置sheet的名称,以及单元格字段信息
        $objPHPExcel->getActiveSheet()->setTitle('test'); //获取当前的工作表并且设置工作表名称
        $objPHPExcel->setActiveSheetIndex(0) //设置sheet（工作表）的起始位置为0
            ->setCellValue('A1', 'sku')  //设置单元格字段信息
            ->setCellValue('B1', '总数');
        // ->setCellValue('C1', '商品价钱');

        //6.设置内容
        $count = count($merge_sku_new);  //计算有多少条数据
        //设置内容 i=2表示从第二段开始设值
        for ($i = 2; $i <= $count + 1; $i++) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $merge_sku_new[$i - 2]['sku']);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $merge_sku_new[$i - 2]['count']);
        }

        //7.通过PHPExcel_IOFactory的写函数将上面数据写出来
        $PHPWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");

        //8.设置表格文件的名称
        $outputFileName = date('YmdHis') . '.xls';

        header("Content-Type: application/force-download");

        header("Content-Type: application/octet-stream");

        header("Content-Type: application/download");

        header('Content-Disposition:inline;filename="' . $outputFileName . '"');

        header("Content-Transfer-Encoding: binary");

        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");

        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

        header("Pragma: no-cache");
        //9.生成并下载表格
        $PHPWriter->save("php://output");
    }
}
